Reputation: 265
I have a problem with Regular Expressions. I want to replace
$[.....] to ${.....}. Only where there is a '$' before '{'.
The following code do almost what I want :
Regex myRegex = new Regex(@"\$\[[^\]]+", RegexOptions.Multiline);
string myString = "voici le [contenu] de $[ma chaine de caractères] dans un contexte précis $[pour faire des essais] de remplacement";
while (myRegex.Match(myString).Success)
{
Console.WriteLine(myString);
Console.WriteLine("");
string myOudString = myRegex.Match(myString).Value+"]";
Console.WriteLine("myOudString is " + myOudString);
string myNewString = myOudString.Replace("[", "{");
myNewString = myNewString.Replace("]", "}");
myString = myString.Replace(myOudString, myNewString);
}
But I have a problem with certain string. For example :
string myString = "Here is $[a sample [of] code] to $[replace different] character"
My code will return :
"Here is ${a sample {of} code} to ${replace different} character".
But I want to return :
"Here is ${a sample [of] code} to ${replace different} character
I hope that anybody can help me.
Thanks!
Upvotes: 1
Views: 563
Reputation: 837946
It is tricky to contrust a "regular" expression for nested parentheses.
If you can assume that there is a maximum one level of nesting then this should work for you:
myString = Regex.Replace(myString, @"\$\[((?:\[.*?\]|.)*?)\]", "${$1}");
Upvotes: 2