小编pro*_*oko的帖子

转义Java MessageFormat的单引号

关于MessagingFormat一般有几个问题,但我还没有发现任何可以解答我问题的问题.我知道,单引号会破坏模式.如果您使用MessageFormat或Log4j,"不"可能会破坏可能的占位符.

请参阅字符串中的一对单引号可用于引用除单引号之外的任何任意字符.例如,模式字符串"'{0}'"表示字符串"{0}",而不是FormatElement.单引号本身必须在整个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));
}
Run Code Online (Sandbox Code Playgroud)

输出:

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

因此,如果我使用正则表达式替换所有单引号,它将起作用.我只是编写了正则表达式,试图仅使用正则表达式lookahead/lookbehind替换"single singlequotes".

正则表达式替换示例:

    doesn't -> doesn''t
    doesn''t -> …
Run Code Online (Sandbox Code Playgroud)

java messageformat

8
推荐指数
4
解决办法
1万
查看次数

标签 统计

java ×1

messageformat ×1