When I run this code:

String.format('Dear {0}, Don\'t forget .... {1} .... {2}', args);

Token 0 is replaced, but token 1 and 2 appear as {1} and {2}

This is caused by the backslash escaping the single quote by the t character.

My work around it to do this:

String.format('Dear {0}, Don`t forget .... {1} .... {2}', args);

But I would like to know how I could escape the ' character without breaking the merging of the arguments?


String.format() uses a Java MessageFormat under the hood. One of the consequences of that is, well, this:

Within a String, a pair of single quotes can be used to quote any arbitrary characters except single quotes. For example, pattern string "'{0}'" represents string "{0}", not a FormatElement. A single quote itself must be represented by doubled single quotes '' throughout a String. For example, pattern string "'{''}'" is interpreted as a sequence of '{ (start of quoting and a left curly brace), '' (a single quote), and }' (a right curly brace and end of quoting), not '{' and '}' (quoted left and right curly braces): representing string "{'}", not "{}".

Your single quote is treated as the start of a quoting region that prevents the formatter from interpreting the substitution variables {1} and {2}.

Basically, double all your single quotes in order to protect them from the formatting machinery. Since Apex, unlike Java, uses single quotes to delimit the string itself, you'll end up with \'\'. The backslash defends the single quote against the Apex parser, and the doubled single quote defends it against the Java formatter.

Further hilarity from the same Java documentation:

The rules for using quotes within message format patterns unfortunately have shown to be somewhat confusing

  • Very very helpful its not confusing its super confusing : ). Thank you for the explanation ! – Boris Borovski Jan 7 at 9:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.