Can I escape braces in a java MessageFormat?
Asked Answered
S

5

78

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}"?

Super answered 27/7, 2009 at 8:39 Comment(0)
P
119

You can put them inside single quotes e.g.

'{'return {2};'}'

See here for more details.

Porty answered 27/7, 2009 at 8:42 Comment(0)
B
18

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}'''".

Bushing answered 27/7, 2009 at 8:43 Comment(1)
Looking for "escap" in this documentation link you posted yields zero results, so the documentation should be updated to include that obvious term, so I don't quite get that "Wow. Surprise!" sarcastic phrase. People read documentations differently, some use Ctrl + F, others not, you have to accept that.Carrizales
P
14

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.

Protolanguage answered 27/7, 2009 at 8:43 Comment(0)
A
2
System.out.println(MessageFormat.format("I want to see ticks and curly braces around '''{'{0}'}'''", "this"));
Avion answered 5/7, 2012 at 22:33 Comment(1)
It would be helpful to see what exactly the result of this would be.Isolating
P
-3

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'
Pelorus answered 8/10, 2018 at 11:58 Comment(1)
I don't see how this is relevant to a Java questionSuper

© 2022 - 2024 — McMap. All rights reserved.