0

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.

2 Answers 2

1

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}");
Sign up to request clarification or add additional context in comments.

Comments

1

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}");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.