Pages

Friday, March 25, 2011

APEX String.format(); Syntax - escaping single quotes

The Apex String method format() is my preferred way to build up a string in the absence of something like a .NET StringBuilder.

The help docs are currently a bit lightweight on detail:

Treat the current string as a pattern that should be used for substitution in the same manner as apex:outputText.

The apex:outputText documentation says:

The value attribute supports the same syntax as the MessageFormat class in Java. See the MessageFormat class JavaDocs for more information.

The syntax in Eclipse appears as: String.format(String pString, List pLIST:String) String

Usage is a format string followed by the substitution arguments as an array.

String formattedString = String.format('Hello {0}, shall we play a {1}?', new String[]{'David', 'game'});
System.debug(formattedString);

Apex String.format and escaped single quotes

String.format(); can be a bit fiddly when it comes to outputting single quotes. A solitary escaped single quote will be lost from the output and prevent further string substitutions.

For Example:

String formattedString = String.format('Hello {0}, shall we play a \'{1}\'?', new String[]{'David', 'game'});
System.debug(formattedString);

Will result in:

Hello David, shall we play a {1}?

The java.text.MessageFormat documentation says:

Within a String, "''" represents a single quote. A QuotedString can contain arbitrary characters except single quotes; the surrounding single quotes are removed.

Example with the escaping to produce the expected output:

String formattedString = String.format('Hello {0}, shall we play a \'\'{1}\'\'?', new String[]{'David', 'game'});  
System.debug(formattedString); 

Will result in:

Hello David, shall we play a 'game'?

See Also:

2 comments:

  1. Try escaping the curly brace!

    Frustrated with escaping single-quotes to quote to brace as suggested by the Java doc, I just tried '{0}{1}{2}', new string[] { '{', userinfo.getuserid(), '}' }

    ReplyDelete
  2. Good idea Thomas. Moving the escaped single quote to the string array works equally well.

    String formattedString = String.format('Hello {0}, shall we play a {2}{1}{2}?', new String[]{'David', 'game', '\''});
    System.debug(formattedString);

    ReplyDelete