转义 Java MessageFormat 的单引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17544794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Escaping single quotes for Java MessageFormat
提问by proko
There are already several questions about the MessagingFormat in general, but I haven't found anything yet that answers my question. I'm aware, that single quotes will break the pattern. If you use MessageFormat or Log4j something like "doesn't" can break possible placeholders.
一般来说,已经有几个关于 MessagingFormat 的问题,但我还没有找到任何可以回答我的问题的问题。我知道,单引号会破坏模式。如果您使用 MessageFormat 或 Log4j 之类的“不”可能会破坏可能的占位符。
Simple example:
简单的例子:
@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));
}
Output:
输出:
Testpattern doesnt show values ( {1}, {2}, {3}, {4} )
Replaced singlequotes: Testpattern doesn't show values ( 100, 200, 300, 400 )
So, if I replace all single quotes using a regular expression, it will work. I just made up the regular expression trying to only replace "single singlequotes" using regular expression lookahead/lookbehind.
因此,如果我使用正则表达式替换所有单引号,它将起作用。我刚刚编写了正则表达式,试图仅使用正则表达式前瞻/后视替换“单引号”。
Regular expression replace examples:
正则表达式替换示例:
doesn't -> doesn''t
doesn''t -> doesn''t
doesn'''t -> doesn'''t
I just wonder, if any apache-commons utility (or any other library) exists, which will handle the "escapeSingleQuotes" for me instead of providing my own regular expression...?
我只是想知道,是否存在任何 apache-commons 实用程序(或任何其他库),它将为我处理“escapeSingleQuotes”而不是提供我自己的正则表达式......?
采纳答案by proko
Since I haven't found another API which would provide the escaped Singlequote (' -> '') I will stay with my regular expression.
由于我还没有找到另一个可以提供转义单引号 (' -> '') 的 API,我将保留我的正则表达式。
回答by Mat
It helped me to do something like this:
它帮助我做这样的事情:
`doesn''t`
回答by Max Hodges
The recommendation from ICU is to use the ASCII apostrophe (' U+0027) only for escaping syntax characters, and use the pretty single quote (' U+2019) for actual apostrophes and single quotes in a message pattern.
ICU 的建议是仅将 ASCII 撇号 (' U+0027) 用于转义语法字符,并将漂亮的单引号 (' U+2019) 用于消息模式中的实际撇号和单引号。
回答by Uriel Frankel
For everyone that has Androidproblems in the string.xml, use \'\' instead of single quote.
对于在string.xml 中遇到Android问题的每个人,请使用 \'\' 而不是单引号。
回答by Alpesh Gediya
Use the escapeEcmaScript method from Apache Commons Lang package.
使用 Apache Commons Lang 包中的 escapeEcmaScript 方法。
See Stack Overflow questions:
请参阅堆栈溢出问题: