仅用正则表达式替换某些组 [英] Replace only some groups with Regex

查看:14
本文介绍了仅用正则表达式替换某些组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下正则表达式:

Let's suppose I have the following regex:

-(d+)-

并且我想使用 C# 将 Group 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 组更改为 this text,将第 2 组更改为 another text...

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.

它应该适用于:

anything(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆