Can I escape braces in a java MessageFormat?

JavaEscapingMessageformat

Java Problem Overview


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

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

Is there a way of escaping the braces surrounding "return {2}"?

Java Solutions


Solution 1 - Java

You can put them inside single quotes e.g.

'{'return {2};'}'

See here for more details.

Solution 2 - Java

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

> Within a String, "''" represents a > single quote. A QuotedString can > contain arbitrary characters except > single quotes; the surrounding single > quotes are removed. An UnquotedString > can 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}'''".

Solution 3 - Java

Use single quotes:

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

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

> Thus, a string that should result in > the formatted message "'{0}'" can be > written as "'''{'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.

Solution 4 - Java

System.out.println(MessageFormat.format("I want to see ticks and curly braces around '''{'{0}'}'''", "this"));

Solution 5 - Java

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}:

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'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSteve BosmanView Question on Stackoverflow
Solution 1 - JavaBrian AgnewView Answer on Stackoverflow
Solution 2 - JavaBombeView Answer on Stackoverflow
Solution 3 - JavaJon SkeetView Answer on Stackoverflow
Solution 4 - JavaVictor RodriguezView Answer on Stackoverflow
Solution 5 - JavaAndreas HeissenbergerView Answer on Stackoverflow