仅用正则表达式替换某些组 - 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:我想使用 C# 将 Group 1 (\\d+)替换为AA ,以获得:

-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.但是我真的不喜欢这样,因为如果我更改模式以匹配_(\\d+)_ ,我将不得不通过_AA_更改替换字符串,这违反了 DRY 原则。

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 ...保持匹配文本的原样,但将第 1 组更改this text ,将第 2 组更改为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. anything(\\d+)more_text和您可以想象的任何模式。

All I want to do is replace only groups, and keep the rest of the match.我想要做的就是只替换组,并保留比赛的其余部分。


解决方案:

参考一: https://en.stackoom.com/question/PCKf
参考二: https://stackoom.com/question/PCKf
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章