Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex.Replace ignoring non-capturing group

Tags:

c#

.net

regex

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?

like image 371
MaYaN Avatar asked Dec 20 '22 03:12

MaYaN


1 Answers

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

like image 84
Avinash Raj Avatar answered Dec 21 '22 16:12

Avinash Raj