Regex replace multiple groups

后端 未结 4 1429
-上瘾入骨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:10

    Similar to Jamiec's answer, but this allows you to use regexes that don't match the text exactly, e.g. \. can't be used with Jamiec's answer, because you can't look up the match in the dictionary.

    This solution relies on creating groups, looking up which group was matched, and then looking up the replacement value. It's a more complicated, but more flexible.

    First make the map a list of KeyValuePairs

    var map = new List>();           
    map.Add(new KeyValuePair("\.", "dot"));
    

    Then create your regex like so:

    string pattern = String.Join("|", map.Select(k => "(" + k.Key + ")"));
    var regex = new Regex(pattern, RegexOptions.Compiled);
    

    Then the match evaluator becomes a bit more complicated:

    private static string Evaluator(List> map, Match match)
    {            
        for (int i = 0; i < match.Groups.Count; i++)
        {
            var group = match.Groups[i];
            if (group.Success)
            {
                return map[i].Value;
            }
        }
    
        //shouldn't happen
        throw new ArgumentException("Match found that doesn't have any successful groups");
    }
    

    Then call the regex replace like so:

    var newString = regex.Replace(text, m => Evaluator(map, m))
    

提交回复
热议问题