Created
October 26, 2024 03:21
-
-
Save davidlfox/68b45c06ba2e9003aaa4475dc6f48557 to your computer and use it in GitHub Desktop.
how to organize generated regex partials and use them elsewhere
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.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