仅更换某些群体与正则表达式 [英] Replace only some groups with Regex
问题描述
让我们假设我有以下的正则表达式:
Let's suppose I have the following regex:
-(\d+)-
和我想更换,使用C#,集团1 (\\ d +)
与 AA
,获得
and I want to replace, using C#, the Group 1 (\d+)
with AA
, to obtain:
-AA-
现在我用替换它:
var text = "example-123-example";
var pattern = @"-(\d+)-";
var replaced = Regex.Replace(text, pattern, "-AA-");
但我真的不喜欢这一点,因为如果我改变的模式来匹配 _(\\ d +)_
相反,我将不得不更改替换字符串 _AA _
过了,这是违反了DRY原则。
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.
我在寻找类似:
请匹配的文本它究竟是怎么回事,但更改1组由
... 本文
和2组其他文本
Keep the matched text exactly how it is, but change Group 1 by this text
and Group 2 by another text
...
编辑:结果
这只是一个例子。我只是在寻找做我上面所说的通用方法。
That was just an example. I'm just looking for a generic way of doing what I said above.
这应该工作:
东西(\\ d +)more_text
键,你能想象的任何图案。
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.
推荐答案
一个好主意,可能是里面封装一切群体,不管需要识别它们。这样,你可以在替换字符串中使用它们。例如:
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");
或使用MatchEvaluator:
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 +)(?= - )
这篇关于仅更换某些群体与正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!