Replace only some groups with Regex

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.

8 Answers
8

Leave a Comment