I want to use a look-ahead regex for replacement with the System.Text.RegularExpression.Replace(...)
method.
Now I am wondering what's wrong. Look at this example code:
string input = "stackoverflow";
string replacement = "#";
var pattern1 = "(?=[a-z])o";
var result1 = Regex.Replace(input, pattern1, replacement);
// result1 = stack#verfl#w (as expected)
var pattern2 = "(?=[a-k])o";
var result2 = Regex.Replace(input, pattern2, replacement);
// result2 = stackoverflow (expected: stack#overflow)
var pattern3 = "(?=k)o";
var result3 = Regex.Replace(input, pattern3, replacement);
// result3 = stackoverflow (expected: stack#overflow)
var pattern4 = "[a-k]";
var result4 = Regex.Replace(input, pattern4, replacement);
// result4 = st###ov#r#low (as expected)
var pattern5 = "([a-k])o";
var result5 = Regex.Replace(input, pattern5, "$1#");
// result5 = stack#verflow" (as expected)
That is very odd.
I can use [a-z]
in my look ahead expression but not [a-k]
or even k
.
What I really want is the result of the last example (pattern5). This is a woraround, but I am corious, why pattern2 or pattern3 don't return the expected. results.