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.
You can do this using lookahead and lookbehind:
I also had need for this and I created the following extension method for it:
Usage:
Result:
If you don't want to change your pattern you can use the Group Index and Length properties of a matched group.
Here is another nice clean option that does not require changing your pattern.
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:
or using a MatchEvaluator:
Another way, slightly messy, could be using a lookbehind/lookahead:
(?<=-)(\d+)(?=-)
go through the below coding to get the separate group replacement.