Skip to content

Instantly share code, notes, and snippets.

@ssta604
Created May 13, 2023 05:59
Show Gist options
  • Save ssta604/d38f4c1e68d7984c7f53d48ff207ce68 to your computer and use it in GitHub Desktop.
Save ssta604/d38f4c1e68d7984c7f53d48ff207ce68 to your computer and use it in GitHub Desktop.
using System.Text.RegularExpressions;
using System.Linq;
/// <summary>
/// Helper class for handling regular expressions.
/// </summary>
public static class RegExHelper
{
/// <summary>
/// Finds matches in the input text based on the search text, treating each word in the search text as a separate pattern.
/// </summary>
/// <param name="inputText">The text to search within.</param>
/// <param name="searchText">The text containing words to search for. Each word is treated as a separate pattern.</param>
/// <returns>A MatchCollection containing all matches found. Returns null if the search text is null or whitespace.</returns>
public static MatchCollection GetRegExMatches(string inputText, string searchText)
{
if (string.IsNullOrWhiteSpace(searchText))
{
return null;
}
var safeSearchText = string.Join("|", searchText.Split(' ').Select(word => Regex.Escape(word)));
if (!string.IsNullOrWhiteSpace(safeSearchText))
{
return Regex.Matches(inputText, safeSearchText, RegexOptions.IgnoreCase);
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment