Fast multi-string replacement

c#, regex

Solution

You can replace all this with

var r = new Regex(string.Join("|", substitutions.Keys.Select(k => "(" + k + ")")));     
return r.Replace(s, m => substitutions[m.Value]);

The key things are making use of the `string.Join` method rather than implementing it yourself, and making use of this `Regex.Replace` overload and delegates to do the replacement.

Problem

I need to perform multi string replacement. I have a string where several parts need to be changed according to substitution map. All replacement must be done in one action - it means if "`a`" should be replaced with "`b`" and also "`b`" must be replaced with "`c`" and input string is "`abc`", the result will be "`bcc`" I have a sollution based on building regex and then replacing all matches. I wrote it some time ago, now I'm refactoring the code and not so satisfied with it. Is there better (faster, simplier) sollution? This is what I have: ``` public static string Replace(string s, Dictionary<string, string> substitutions) { string pattern = ""; int i = 0; foreach (string ch in substitutions.Keys) { if (i == 0) pattern += "(" + Regex.Escape(ch) + ")"; else pattern += "|(" + Regex.Escape(ch) + ")"; i++; } var r = new Regex(pattern); var parts = r.Split(s); string ret = ""; foreach (string part in parts) { if (part.Length == 1 && substitutions.ContainsKey(part[0].ToString())) { ret += substitutions[part[0].ToString()]; } else { ret += part; } } return ret; } ``` And test case: ``` var test = "test aabbcc"; var output = Replace(test, new Dictionary<string, string>{{"a","b"},{"b","y"}}); Assert.That(output=="test bbyycc"); ```

Original source