Neilski
Neilski

Reputation: 4415

Regex - Replacing part of a number string

I have the following scenario:

string source1 "ABC?XYZ";
string source2 "DEF?PQR";
string replacement = "123"
string result = Regex.Replace(source1, @"([A-Z]{3,})(\?+)([A-Z]{3,})", "$1" + replacement + "$3");

The problem is of course, that the replacement string expands to "S1123$3" which confuses the parser as it tries to find $1123.

Can anyone tell me how the elements can be delimited from the replacement string?

Thanks.

Upvotes: 0

Views: 160

Answers (2)

Paolo Stefan
Paolo Stefan

Reputation: 10253

The problem is that if you concatenate "$1" + replacement + "$3", it gives "$1123$3". The regex parser will try to replace the 1123rd capturing group, thus it won't do anything.

If the conventions of PHP are valid in the language you code (see here), you can accomplish what you want by changing the $n replacement references to ${n}, like this :

string result = 
  Regex.Replace( source1, @"([A-Z]{3,})(\?+)([A-Z]{3,})",
                 "${1}" + replacement + "${3}");

Upvotes: 1

Igor Korkhov
Igor Korkhov

Reputation: 8558

Use ${n} instead of $n, i.e. ${1} and ${3} in your example:

string result = Regex.Replace(source1, @"([A-Z]{3,})(\?+)([A-Z]{3,})", "${1}" + replacement + "${3}");

Upvotes: 1

Related Questions