Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

c# - 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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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+)(?=-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...