Phase 17 of 30 · Topic 17.4

Source Generated Regular Expressions ([GeneratedRegex])

1Concept

The [GeneratedRegex] attribute compiles regular expressions into specialized C# character matching loops at compile time, bypassing runtime regex parsing and regex interpreter overhead.

2Architecture Diagram

Regex.IsMatch(input, "^[A-Z0-9]+$") ──> Runtime parsing & state machine allocation
[GeneratedRegex("^[A-Z0-9]+$")]   ──> Compiles to raw C# while-switch loops with AVX2 SIMD checks!

3Code Example

C# 13 & .NET 9
using System;
using System.Text.RegularExpressions;

public partial class RegexUtility
{
    // Source Generated Regex
    [GeneratedRegex(@"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$", RegexOptions.IgnoreCase)]
    public static partial Regex EmailRegex();
}

public class GeneratedRegexDemo
{
    public static void Main()
    {
        bool isValid = RegexUtility.EmailRegex().IsMatch("contact@careeraipro.com");
        Console.WriteLine($"Is Valid Email (Compiled C# Regex): {isValid}");
    }
}

4Expected Output

Is Valid Email (Compiled C# Regex): True

5Key Takeaways

  • Always replace runtime `new Regex()` with `[GeneratedRegex]` partial methods.
  • RyuJIT vectorizes generated regex character matching loops using SIMD.
  • Catches invalid regex syntax errors at compile time.