Can I avoid curly braces in java MessageFormat?

I want to output some curly braces in java MessageFormat. For example, I know that the following does not work:

MessageFormat.format(" public {0} get{1}() {return {2};}\n\n", type, upperCamel, lowerCamel); 

Is there any way to avoid parentheses around "return {2}"?

+61
java escaping messageformat
Jul 27 '09 at 8:39
source share
5 answers

You can put them in single quotes, for example,

 '{'return {2};'}' 

See here for more details.

+91
Jul 27 '09 at 8:42
source share

Wow. Surprise! The documentation for MessageFormat knows the answer:

Inside String "''" is a single quote. The QuotedString function can contain arbitrary characters except single quotes; ambient single quotes are deleted. UnquotedString can contain arbitrary characters besides single quotes and left curly brackets. Thus, the string that should lead to the formatted message "'{0}'" can be written as "'''{'0}''" or "'''{0}'''" .

+16
Jul 27 '09 at 8:43
source share

Use single quotes:

 MessageFormat.format(" public {0} get{1}() '{'return {2};'}'\n\n", type, upperCamel, lowerCamel); 

If you want to actually use one quote, just double it. The JavaDoc for MessageFormat gives this somewhat complex example:

Thus, a string that needs a formatted message "'{0}'" can be written as "'''{'0}''" or "'''{0}'''" .

This value is '' for a single quote, then '{' for an escaped curly brace, then 0 , '}' for a closing curly brace and '' for a closing quote.

+12
Jul 27 '09 at 8:43
source share
 System.out.println(MessageFormat.format("I want to see ticks and curly braces around '''{'{0}'}'''", "this")); 
+2
Jul 05 2018-12-12T00:
source share

You can use this regular expression with a pearl or any other language to remove curly braces and single quotes (x27). This does not apply to any placeholder, for example {0} : bash 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$1/g; s/([^0-9])\}/$1\x27\}\x27/g' bash 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$1/g; s/([^0-9])\}/$1\x27\}\x27/g'

0
Oct 08 '18 at 11:58
source share



All Articles