Replace only some groups with Regex

Oscar Mederos picture Oscar Mederos · May 15, 2011 · Viewed 126.4k times · Source

Let's suppose I have the following regex:

-(\d+)-

and I want to replace, using C#, the Group 1 (\d+) with AA, to obtain:

-AA-

Now I'm replacing it using:

var text = "example-123-example";
var pattern = @"-(\d+)-";
var replaced = Regex.Replace(text, pattern, "-AA-"); 

But I don't really like this, because if I change the pattern to match _(\d+)_ instead, I will have to change the replacement string by _AA_ too, and this is against the DRY principle.

I'm looking for something like:

Keep the matched text exactly how it is, but change Group 1 by this text and Group 2 by another text...

Edit:
That was just an example. I'm just looking for a generic way of doing what I said above.

It should work for:

anything(\d+)more_text and any pattern you can imagine.

All I want to do is replace only groups, and keep the rest of the match.

Answer

bluepnume picture bluepnume · May 15, 2011

A good idea could be to encapsulate everything inside groups, no matter if need to identify them or not. That way you can use them in your replacement string. For example:

var pattern = @"(-)(\d+)(-)";
var replaced = Regex.Replace(text, pattern, "$1AA$3"); 

or using a MatchEvaluator:

var replaced = Regex.Replace(text, pattern, m => m.Groups[1].Value + "AA" + m.Groups[3].Value);

Another way, slightly messy, could be using a lookbehind/lookahead:

(?<=-)(\d+)(?=-)