11

Is there a way to escape curly braces within String.format?

E.g. if I want to get the following output:

{777}

I'd expected {{ would do the job but this code throws an exception:

String.format('{{{0}}}', new String[] { String.valueOf(777) });

can't parse argument number: {{0}}

Thanks in advance!

2 Answers 2

14

This is how this is done

System.debug(LoggingLevel.INFO,String.format('\'{\'{0}\'}\'', 
     new String[] { String.valueOf(777) }));

produces {777}

SFDC String.format (also used by VF apex:outputtext) uses the Java MessageFormat class. And braces are escaped by enclosing in single quotes, which in apex must also be escaped by backslash.

See https://stackoverflow.com/questions/1187093/can-i-escape-braces-in-a-java-messageformat

0
0

Actually what String.format method do is it finds a number within a combination of two braces. In your case the orginal string is {{{0}}} and so it finds "{{0}}" this string within first combination of braces and so its trying to parse it in a number and thats why showing a parsing error coz "{{0}}" cannot be converted in number.

You can use any other string methods like substitute etc. to do the same.

3
  • In c# that's what it would look like and it would work: string.Format("{{{0}}}", someString) would result in {someStringValue}. I'm trying to do the same in Apex.
    – user39399
    Jun 2, 2015 at 12:49
  • Yes I understood your point, but may be the string class & its method implementation is different as compared to the string class in C#, that could be a reason.
    – Nebula
    Jun 2, 2015 at 12:59
  • But what if there's a way to escape them in Apex as well? :)
    – user39399
    Jun 2, 2015 at 13:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .