I have the following code:
var pattern = @"(?:red).*(\d+)";
var regX = new Regex(pattern);
var input = "this is red with number 111";
var replaced = regX.Replace(input, "666");
The replaced
is then: this is 666
instead of: this is red with number 666
Why is this happening?
You need to use positive lookbehind assertion based regex since (?:red).*
part of your regex matches characters. So when replacing, all the matched chars got replaced.
var pattern = @"(?<=red.*?)\d+";
var regX = new Regex(pattern);
var input = "this is red with number 111";
var replaced = regX.Replace(input, "666");
OR
Use capturing groups.
var pattern = @"(red.*?)\d+";
Replace the matched chars with $1
or \1
+ 666
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