Escape curly braces {in line to support String.Format

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

A string contains any combination of these curly braces, so essentially the method should go through the string and calculate if "{" has a closing, and if together they form a valid place holder for String.Format (ie {5}), those which should not be shielded correctly.

I can write a method for this, but wondered if there is anything built into .NET, or is there something that already does this?

An example line is as follows:

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

As you can tell, submitting this to String.Format will throw an exception in {or contact us at: XXXX}

+5
source share
3 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 lines that should not be escaped have a format {\d+}.

There are two caveats here. First, we may run into already runaway curvy braces - {{. This is easier to fix: add more hits ...

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

... in other words, when trying to replace the bracket, make sure that it is alone. )

-, , , , , . , beasty , , } :

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

, , (, ), , .

: , , { }, - , :

Regex firstPass = new Regex("(\\{(?!\\d+[^} ]*}))");
string firstPassEscape = "{$1";
...
Regex secondPass        = new Regex("((?<!\\{\\d+[^} ]*)})");
string secondPassEscape = "$1}";
+2

escape- ? , !

, - . , string.Format.

var s = string.Format("Hello {0} please ... {{or contact}}", customer.Name );
// Now use s as needed 
// now is: "Hello Joe please ... {or contact}"
0

Try:

myString = Regex.Replace(myString, @"\{(\D+)\}", "{{$1}}");
0
source

All Articles