I think regex will be so fragile for this kind of thing. If your version of .NET has extension methods and you need more syntax that can scale, you can introduce an extension method as follows:
public static class StringExtensions { public static string ReplaceMany(this string s, Dictionary<string, string> replacements) { var sb = new StringBuilder(s); foreach (var replacement in replacements) { sb = sb.Replace(replacement.Key, replacement.Value); } return sb.ToString(); } }
So now you are creating a replacement dictionary ...
var replacements = new Dictionary<string, string> { {"(", "-"}, {")", ""} };
And call ReplaceMany:
var result = "foobar(baz2)".ReplaceMany(replacements);
If you really want to show your intent, you can do an alias Dictionary<string,string> before StringReplacements :
//At the top using StringReplacements = System.Collections.Generic.Dictionary<string,string>; //In your function var replacements = new StringReplacements() { {"(", "-"}, {")", ""} }; var result = "foobar(baz2)".ReplaceMany(replacements);
There may be an excess for only two replacements, but if you have a lot of them, it will be cleaner than .Replace().Replace().Replace().Replace()...
Jason punyon
source share