Given the following:
string input = "xSxSx";
var result = Regex.Replace(input, "xSx", "xTx");
// result == "xTxSx"
It looks like the replacement string is not used for further matching, which is why we don't get the expected "xTxTx".
How to solve that? Is there some kind of special notation to tell the engine to find for a second match using the string with the first replacement already in place?
That's because, once a character is matched, it won't be matched again. So, 2nd time the string to match is Sx and not xSx.
You would need to use look-arounds here:
Regex.Replace(input, "(?<=x)S(?=x)", "T");
This will replace the S which is both preceded and succeeded by x with a T. Since look-arounds are 0-length assertion, they will not consume x.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With