using System; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace CTA.WebForms.Extensions { public static class RegexExtensions { /// /// Allows for regex replacements using async function delegates. /// /// The regular expression that is being used. /// The string that is being applied to. /// The function that is used for match replacement. /// The input string with all matches made by the regular expression /// replaced as specified in the replacement function. public static async Task ReplaceAsync(this Regex regex, string input, Func> replacementFn) { var sb = new StringBuilder(); var lastIndex = 0; foreach (Match match in regex.Matches(input)) { sb.Append(input, lastIndex, match.Index - lastIndex) .Append(await replacementFn(match).ConfigureAwait(false)); lastIndex = match.Index + match.Length; } sb.Append(input, lastIndex, input.Length - lastIndex); return sb.ToString(); } } }