繁体   English   中英

转义Java MessageFormat的单引号

[英]Escaping single quotes for 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));
}

输出:

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

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

正则表达式替换示例:

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

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

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

`doesn''t`

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

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

对于在string.xml中遇到Android问题的每个人,请使用\\'\\'而不是单引号。

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

请参阅Stack Overflow问题:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM