[GeneratedRegex]: Your Regex, but Make It Fast

Regex in .NET has always been powerful, but let’s be honest, every time you write new Regex(pattern) you feel a tiny pang of guilt about the runtime compilation cost. And if you’re using Regex.IsMatch() with a string literal in a loop? That’s a performance review waiting to happen. [GeneratedRegex] fixes all of this by source-generating your regex at compile time.

The syntax is minimal. Slap the attribute on a partial method that returns Regex, and the compiler does the rest:

using System.Text.RegularExpressions;
var inputs = new[] { "[email protected]", "not-an-email", "[email protected]" };
foreach (var input in inputs)
{
Console.WriteLine(EmailRegex().IsMatch(input)
? $"{input}"
: $"{input}");
}
partial class Program
{
[GeneratedRegex(@"^[^@\s]+@[^@\s]+\.[^@\s]+$", RegexOptions.IgnoreCase)]
private static partial Regex EmailRegex();
}

What happens behind the scenes is pretty slick. The source generator analyzes your pattern and emits a custom Regex-derived class with a hand-optimized TryFindNextPossibleStartingPosition and TryMatchAtCurrentPosition. No interpretation, no runtime compilation. Just raw, ahead-of-time matching logic. This means it’s also fully Native AOT compatible, which new Regex() is not.

You also get free IDE diagnostics. If your pattern has a syntax error, you’ll see it as a compile-time warning, not a runtime ArgumentException thrown at 2 AM in production. The Roslyn analyzer even catches common pitfalls like catastrophic backtracking patterns.

Performance-wise, benchmarks consistently show [GeneratedRegex] matching 2-5x faster than interpreted regex, with zero allocation overhead on the matching path. If you have any static readonly Regex fields in your codebase, migrating them is a five-second refactor with a massive payoff. Your patterns deserve the VIP treatment.