You need to sign in to do that
Don't have an account?
How to escape braces in a string format.
I have a use case where I need to do some string substitution on a string that has brace characters {}. What is the proper way to escape the braces to make this test pass?
public static testMethod void StringFormatFailsWithBraces()
{
List<string> substitutions = new List<String>();
substitutions.add('world');
string result = string.format('{hello {0}}', substitutions);
System.assertEquals('{hello world}', result);
}
Below is the very interesting exception which leads to demo.icu-project.org, which doesn't tell me any information.
System.StringException: All argument identifiers have to be either non-negative numbers or strings following the pattern ([:ID_Start:] [:ID_Continue:]*).
For more details on these unicode sets, visit http://demo.icu-project.org/icu-bin/ubrowse
Thanks!
Matt
Finally got it to work. You have to put the braces in the Format List :-
All Answers
Try this :-
string result = string.format('\{hello {0}\}', substitutions);
Thanks, I had tried this. But this produces a different error "Invalid string literal '\{helllo {0}\}'. Illegal character sequence '\{' in string literal.
Finally got it to work. You have to put the braces in the Format List :-
Thanks! I'm sure that would work, but it doesn't actually help my situation.
This is exactly what I did. A bunch of string constants to escape out the ones that are part of a format and the ones that are not part of a format. Then some well placed string.replace functions.
If salesforce were looking for ideas on how better to handle this, I highly recommend what C# has done, which is shown below:
Assert.That(string.Format("{{hello {0}}}", "world"), Is.EqualTo("{hello world}"));