0

How to escape curly braces in a dynamic string variable, which is used in String.Format?

Edit 1

I am aware of how this can be handled when the value of the string is known. for e.g.

string someStringVar = "This is a random string {0}. Blah {{ Blah {{ Blah }}"

But how to handle it when I am not aware of the strings value. for e.g.

string someStringVar = GetValueFromXmlFile();

In the above code, GetValueFromXmlFile method could return a string with a valid placeholder like {0} but could also contain characters like { or } which are not placeholders? In such a case should one escape { or } without escaping valid placeholder like {0}?

surajnaik
  • 725
  • 2
  • 10
  • 26
  • 1
    Please show an example of what are you trying to do. – Steve Jul 11 '16 at 08:43
  • If the string is designed to be a format placeholder that it should _already_ have curly braces escaped and be ready for use as a format string. You should solve the problem _there_ instead of adding a bunch of risky, brittle logic to try and guess what should be escaped and what shouldn't. – D Stanley Jul 11 '16 at 13:39

1 Answers1

0

You can replicate all curly braces and than fix the ones you do not want to be escaped:

var duplicateLeftCurlyBrackets = Regex.Replace(someStringVar, @"([^}]|^)}([^}]|$)", @"$1}}$2");
var duplicatedBothCurlyBrackets = Regex.Replace(duplicateLeftCurlyBrackets, @"([^{]|^){([^{]|$)", @"$1{{$2");
var result = Regex.Replace(duplicatedBothCurlyBrackets, @"{{([0-9]+)}}", @"{$1}");

Can you really assume that the input will be always in the form as seen from your example?