問題:
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