Skip to content

Instantly share code, notes, and snippets.

@davidlfox
Created October 26, 2024 03:21
Show Gist options
  • Save davidlfox/68b45c06ba2e9003aaa4475dc6f48557 to your computer and use it in GitHub Desktop.
Save davidlfox/68b45c06ba2e9003aaa4475dc6f48557 to your computer and use it in GitHub Desktop.
how to organize generated regex partials and use them elsewhere
using System.Text.RegularExpressions;
namespace GeneratedRegexTest;
public static partial class RegexUtilities
{
// define a partial, parameterless method with GeneratedRegex attribute
// pattern to match SSN format (e.g. 123-45-6789)
[GeneratedRegex(@"\b\d{3}-\d{2}-\d{4}\b")]
public static partial Regex SsnRegex();
}
public class Program
{
public static void Main()
{
string text = "Sample SSNs: 123-45-6789, 987-65-4321, and some other text.";
// use the generated regex method to get a regex instance
Regex ssnRegex = RegexUtilities.SsnRegex();
// find all matches in the text
foreach (Match match in ssnRegex.Matches(text))
{
Console.WriteLine($"Found SSN: {match.Value}");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment