Regex replace multiple groups

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

    Given a dictionary like in the other answers, you can use an "aggregate" to map each pattern in the dictionary to a replacement. This will give you far more flexibility that the other answers, as you can have different regex options for each pattern.

    For example, the following code will "romanize" greek text (https://en.wikipedia.org/w/index.php?title=Romanization_of_Greek§ion=3#Modern_Greek, Standard/UN):

    var map = new Dictionary() {
        {"α[ύυ](?=[άαβγδέεζήηίΐϊιλμνόορύΰϋυώω])", "av"}, {"α[ύυ]", "af"}, {"α[ϊΐ]", "aï"}, {"α[ιί]", "ai"}, {"[άα]", "a"},
        {"β", "v"}, {"γ(?=[γξχ])", "n"}, {"γ", "g"}, {"δ", "d"},
        {"ε[υύ](?=[άαβγδέεζήηίΐϊιλμνόορύΰϋυώω])", "ev"}, {"ε[υύ]", "ef"}, {"ει", "ei"}, {"[εέ]", "e"}, {"ζ", "z"},
        {"η[υύ](?=[άαβγδέεζήηίΐϊιλμνόορύΰϋυώω])", "iv"}, {"η[υύ]", "if"}, {"[ηήιί]", "i"}, {"[ϊΐ]", "ï"},
        {"θ", "th"}, {"κ", "k"}, {"λ", "l"}, {"\\bμπ|μπ\\b", "b"}, {"μπ", "mb"}, {"μ", "m"}, {"ν", "n"},
        {"ο[ιί]", "oi"}, {"ο[υύ]", "ou"}, {"[οόωώ]", "o"}, {"ξ", "x"}, {"π", "p"}, {"ρ", "r"},
        {"[σς]", "s"}, {"τ", "t"}, {"[υύϋΰ]", "y"}, {"φ", "f"}, {"χ", "ch"}, {"ψ", "ps"}
    };
    
    var input = "Ο Καλύμνιος σφουγγαράς ψυθίρισε πως θα βουτήξει χωρίς να διστάζει."; 
    map.Aggregate(input, (i, m) => Regex.Replace(i, m.Key, m.Value, RegexOptions.IgnoreCase));
    

    returning (without modifying the "input" variable:

    "o kalymnios sfoungaras psythirise pos tha voutixei choris na distazei."
    

    You can of course use something like:

    foreach (var m in map) input = Regex.Replace(input, m.Key, m.Value, RegexOptions.IgnoreCase);
    

    which does modify the "input" variable.

    Also you can add this to improve performance:

    var remap = new Dictionary();
    foreach (var m in map) remap.Add(new Regex(m.Key, RegexOptions.IgnoreCase | RegexOptions.Compiled), m.Value);
    

    cache or make static the remap dictionary and then use:

    remap.Aggregate(input, (i, m) => m.Key.Replace(i, m.Value));
    

提交回复
热议问题