Regex replace multiple groups

后端 未结 4 1433
-上瘾入骨i
-上瘾入骨i 2020-11-29 06:51

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

Replacement table:

  • \"&\" ->
4条回答
  •  孤街浪徒
    2020-11-29 07:02

    Given a dictionary that defines your replacements:

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

    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
    

    Live example: http://rextester.com/rundotnet?code=ADDN57626

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


    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
    

提交回复
热议问题