Last active
April 19, 2020 15:09
-
-
Save otuncelli/b246b5fe3e9c8885dc6e to your computer and use it in GitHub Desktop.
Replace multiple strings in single pass (based on regular expressions)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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