Skip to content

Instantly share code, notes, and snippets.

@otuncelli
Last active April 19, 2020 15:09
Show Gist options
  • Save otuncelli/b246b5fe3e9c8885dc6e to your computer and use it in GitHub Desktop.
Save otuncelli/b246b5fe3e9c8885dc6e to your computer and use it in GitHub Desktop.
Replace multiple strings in single pass (based on regular expressions)
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace MultiReplace
{
public sealed class StringMultiReplace
{
#region Private Members
private readonly Regex regex;
private readonly Dictionary<string, string> map;
#endregion
#region Constructors
public StringMultiReplace(Dictionary<string, string> map, RegexOptions regexOptions) :
this(map.Keys, regexOptions)
{
this.map = map;
}
public StringMultiReplace(IEnumerable<string> searchPatterns, RegexOptions regexOptions)
{
regex = new Regex("(" + String.Join("|", searchPatterns) + ")", regexOptions);
}
#endregion
#region Public Methods
public string Replace(string input)
{
return regex.Replace(input, m => map[m.Groups[0].Value]);
}
public string Replace(string input, string replacement)
{
return regex.Replace(input, replacement);
}
public string Replace(string input, MatchEvaluator evaluator)
{
return regex.Replace(input, evaluator);
}
#endregion
#region Static Methods
public static string SlowReplace(string input, Dictionary<string, string> map, RegexOptions regexOptions)
{
return new StringMultiReplace(map, regexOptions).Replace(input, m => map[m.Groups[0].Value]);
}
#endregion
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment