Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

escape curly braces { in a string to support String.Format

Tags:

c#

.net

I have strings that I read from the database, these strings are fed into String.Format method, if a string has '{' '}' braces but these braces are not escaped correctly for String.Format (i.e add another '{' to escape them) the String.Format will throw an exception.

The string have any combination of these braces, so in essence the method needs to go through the string and figure out if '{' have a closing one and if together they form a valid place holder for String.Format (i.e. {5}), the ones that don't need to be escaped correctly.

I can write a method to do that, but was wondering if there is anything built into .NET, or anything out there that already does this ?

A string example is the following:

Hello {0}, please refer to our user manual for more information {or contact us at: XXXX}"

As you can tell feeding this into String.Format will throw an exception on the {or contact us at: XXXX}

like image 480
Pacman Avatar asked Nov 04 '22 15:11

Pacman


1 Answers

How about this:

string input = "Hello {0}, please refer for more information {or contact us at: XXXX}";
   Regex rgx = new Regex("(\\{(?!\\d+})[^}]+})");
string replacement = "{$1}";
string result = rgx.Replace(input, replacement);

Console.WriteLine("String {0}", result);

// Hello {0}, please refer for more information {{or contact us at: XXXX}}

... assuming that the only strings that should not be escaped are of format {\d+}.

There are two caveats here. First, we may encounter already-escaped curvy braces - {{. Fix for it is more-o-less easy: add more lookarounds...

Regex rgx = new Regex("(\\{(?!\\d+})(?!\\{)(?<!\\{\\{)[^}]+})");

... in other words, when trying to replace a bracket, make sure it's a lonely one. )

Second, formats themselves may not be so simple - and as the complexity of those that actually may be present in your strings grows, so does the regex's one. For example, this little beasty won't attempt to fix format string that start with numbers, then go all the way up to } symbol without any space in between:

Regex rgx = new Regex("(\\{(?!\\d\\S*})(?!\\{)(?<!\\{\\{)[^}]+})");

As a sidenote, even though I'm the one of those people that actually like to have two problems (well, sort of), I do shudder when I look at this.

UPDATE: If, as you said, you need to escape each single occurrence of { and }, your task is actually a bit easier - but you will need two passes here, I suppose:

Regex firstPass = new Regex("(\\{(?!\\d+[^} ]*}))");
string firstPassEscape = "{$1";
...
Regex secondPass        = new Regex("((?<!\\{\\d+[^} ]*)})");
string secondPassEscape = "$1}";
like image 170
raina77ow Avatar answered Nov 13 '22 18:11

raina77ow