java - 转义 Java MessageFormat 的单引号

标签 java messageformat

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

参见 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 替换所有单引号,它将起作用。我刚刚编写了正则表达式,试图使用正则表达式前瞻/后视仅替换“单引号”。

正则表达式替换示例:

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

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

最佳答案

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

`doesn''t`

关于java - 转义 Java MessageFormat 的单引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17544794/

相关文章:

java - 在Struts中,如何从ResourceBundle中选取ActionMessage中的 'replacement values for message'

java - 如何在没有 Android ICU 的情况下在 ChoiceFormat 中使用 "{0, ordinal}"

java.text.MessageFormat 不带数字分组分隔符

java - 填写预先格式化的文本文件以发送电子邮件 - MessageFormat 替代方案

java - 使用x路径在java中加载xml

java - setOpaque为true,但JPanel不会改变背景颜色

java - 从 java 运行 python 脚本产生 KeyError

java - 关闭 JFreeChart 条形图中的空白区域

java - 为 HTML.UnknownTag 的所有实例注册 TagAction

java - Java MessageFormat 类线程安全吗? (相对于 SimpleDateFormat)