且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

正则表达式替换多个组

更新时间:2022-03-23 22:29:22

由于字典定义你的替换:

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

活生生的例子: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.

据指出,在评论中,由于预期有正则表达式的语法中有一个发现的模式将无法正常工作。这可以通过使用Regex.Escape$c$c>和一个微小的变化到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