我可以在 java MessageFormat 中转义大括号吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1187093/
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
Can I escape braces in a java MessageFormat?
提问by Steve Bosman
I want to output some braces in a java MessageFormat. For example I know the following does not work:
我想在 java MessageFormat 中输出一些大括号。例如,我知道以下不起作用:
MessageFormat.format(" public {0} get{1}() {return {2};}\n\n", type, upperCamel, lowerCamel);
Is there a way of escaping the braces surrounding "return {2}"?
有没有办法转义围绕“return {2}”的大括号?
采纳答案by Brian Agnew
回答by Jon Skeet
Use single quotes:
使用单引号:
MessageFormat.format(" public {0} get{1}() '{'return {2};'}'\n\n",
type, upperCamel, lowerCamel);
If you want to actually usea single quote, just double it. The JavaDoc for MessageFormat
gives this somewhat complicated example:
如果您想实际使用单引号,只需将其加倍即可。在对JavaDoc中MessageFormat
给出了这样的有些复杂例子:
Thus, a string that should result in the formatted message
"'{0}'"
can be written as"'''{'0}''" or "'''{0}'''"
.
因此,应该导致格式化消息的字符串
"'{0}'"
可以写为"'''{'0}''" or "'''{0}'''"
.
This is ''
for a single quote, then '{'
for an escaped brace, then 0
, '}'
for the closing brace and ''
for the closing quote.
这是''
一个单引号,然后'{'
进行转义括号,然后0
,'}'
在右括号,并''
在右引号。
回答by Bombe
Wow. Surprise! The documentation for MessageFormatknows the answer:
哇。惊喜!MessageFormat的文档知道答案:
Within a String,
"''"
represents a single quote. A QuotedStringcan contain arbitrary characters except single quotes; the surrounding single quotes are removed. An UnquotedStringcan contain arbitrary characters except single quotes and left curly brackets. Thus, a string that should result in the formatted message"'{0}'"
can be written as"'''{'0}''"
or"'''{0}'''"
.
在String 中,
"''"
代表单引号。甲QuotedString可以包含除单引号的任意字符; 周围的单引号被删除。一个UnquotedString可以包含除单引号和左大括号的任意字符。因此,应该导致格式化消息的字符串"'{0}'"
可以写为"'''{'0}''"
或"'''{0}'''"
。
回答by Victor Rodriguez
System.out.println(MessageFormat.format("I want to see ticks and curly braces around '''{'{0}'}'''", "this"));
回答by Andreas Heissenberger
you can use this regex with perl or any other language to escape curly brackets and single quotes (x27). It does not touch any placeholder e.g. {0}
:
您可以将此正则表达式与 perl 或任何其他语言一起使用来转义大括号和单引号 (x27)。它不会触及任何占位符,例如{0}
:
echo "# 'single' quote test \n\n public {0} get{1}() {return {2};}\n\n" | perl -pe 's/\x27/\x27\x27/g; s/\{([^0-9])/\x27\{\x27/g; s/([^0-9])\}/\x27\}\x27/g'