正则表达式替换多个组 [英] Regex replace multiple groups

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

问题描述

我想用常规的前pressions更换多组具有相应的替换字符串。

I would like to use regular expressions to replace multiple groups with corresponding replacement string.

替换表:

  • &放大器; - > __amp
  • # - > __hsh
  • 1 - > 5
  • 5 - > 6

例如,对于以下输入字符串

For example, for the following input string

a1asda和放大器; FJ#ahdk5adfls

a1asda&fj#ahdk5adfls

相应的输出字符串是

a5asda__ampfj__hshahdk6adfls

a5asda__ampfj__hshahdk6adfls

有没有办法做到这一点?

Is there any way to do that ?

推荐答案

由于字典定义你的替换:

Given a dictionary that defines your replacements:

IDictionary<string,string> map = new Dictionary<string,string>()
        {
           {"&","__amp"},
           {"#","__hsh"},
           {"1","5"},
           {"5","6"},
        };

您可以使用此既为构造正防爆pression,并形成替代每场比赛:

You can use this both for constructing a Regular Expression, and to form a replacement for each match:

var str = "a1asda&fj#ahdk5adfls";
var regex = new Regex(String.Join("|",map.Keys));
var newStr = regex.Replace(str, m => map[m.Value]);
// newStr = a5asda__ampfj__hshahdk6adfls

活生生的例子:<一href="http://rextester.com/rundotnet?$c$c=ADDN57626">http://rextester.com/rundotnet?$c$c=ADDN57626

这使用了替换 文档过载,它允许你指定一个lambda EX pression用于替换。

This uses a Replace(docs) overload which allows you to specify a lambda expression for the replacement.

据指出,在评论中,由于预期有正则表达式的语法中有一个发现的模式将无法正常工作。这可以通过使用<一个来克服href="http://msdn.microsoft.com/en-us/library/system.text.regularex$p$pssions.regex.escape.aspx"><$c$c>Regex.Escape和一个微小的变化到code以上:

It has been pointed out in the comments that a find pattern which has regex syntax in it will not work as expected. This could be overcome by using Regex.Escape and a minor change to the code above:

var str = "a1asda&fj#ahdk5adfls";
var regex = new Regex(String.Join("|",map.Keys.Select(k => Regex.Escape(k)));
var newStr = regex.Replace(str, m => map[m.Value]);
// newStr = a5asda__ampfj__hshahdk6adfls

这篇关于正则表达式替换多个组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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