转义Java MessageFormat的单引号

时间:2013-07-09 09:31:47

标签: java messageformat

一般来说,关于MessagingFormat已经有几个问题,但我还没有找到任何可以回答我问题的问题。 我知道,单引号会破坏模式。如果您使用MessageFormat或Log4j,“不”可能会破坏可能的占位符。

请参阅Within a String, a pair of single quotes can be used to quote any arbitrary characters except single quotes. For example, pattern string "'{0}'" represents string "{0}", not a FormatElement. A single quote itself must be represented by doubled single quotes '' throughout a String

简单示例:

@Test
public void test() {
    String pattern = "{0} doesn't show values ( {1}, {2}, {3}, {4} )";
    final Object[] args = { "Testpattern", 100, 200, 300, 400 };
    System.out.println(MessageFormat.format(pattern, args));
    pattern = pattern.replaceAll("(?<!')'(?!')", "''");
    System.out.println("Replaced singlequotes: " + MessageFormat.format(pattern, args));
}

输出:

Testpattern doesnt show values ( {1}, {2}, {3}, {4} )
Replaced singlequotes: Testpattern doesn't show values ( 100, 200, 300, 400 )

因此,如果我使用regular expression替换所有单引号,它将起作用。我只是编写正则表达式,尝试仅使用正则表达式lookahead / lookbehind替换“单个单引号”。

正则表达式替换示例:

    doesn't -> doesn''t
    doesn''t -> doesn''t
    doesn'''t -> doesn'''t

我只是想知道,如果存在任何apache-commons实用程序(或任何其他库),它将为我处理“escapeSingleQuotes”而不是提供我自己的正则表达式...?

5 个答案:

答案 0 :(得分:10)

它帮助我做了这样的事情:

`doesn''t`

答案 1 :(得分:5)

ICU的建议是仅使用ASCII撇号(&#39; U + 0027)来转义语法字符,并使用漂亮的单引号('U + 2019)来表示消息模式中的实际撇号和单引号

答案 2 :(得分:3)

由于我还没有找到另一个提供转义单引号的API(' - &gt;''),我将保留我的正则表达式。

答案 3 :(得分:3)

对于 string.xml 中存在 Android 问题的所有人,请使用\&#39; \&#39;而不是单引号。

答案 4 :(得分:0)

使用Apache Commons Lang软件包中的escapeEcmaScript方法。

请参阅Stack Overflow问题: