Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Strings and Text

GeneratedRegex source generator

Reference for the [GeneratedRegex] attribute in C#: compile-time regex code generation on partial methods and properties, options, timeouts and AOT use.

[GeneratedRegex] asks the compiler to write the matching code for a pattern at build time. You declare a partial method (or, in C# 13 with .NET 9, a partial property) that returns Regex, put the attribute on it with the pattern, and the source generator supplies the body. The result is a Regex whose code was produced by the compiler, so there is no pattern parsing or IL emission at run time.

Compared with new Regex(...) the generated version starts faster, matches as fast as RegexOptions.Compiled, works with trimming and Native AOT, and gives you readable C# you can step through. The containing type must be partial. It needs an ordinary project build; one-file online runners such as ours cannot run source generators.

C#
public static partial class Patterns
{
    [GeneratedRegex(@"^\d{5}$", RegexOptions.CultureInvariant)]
    public static partial Regex ZipCode();
}

Try it

The runner on this site compiles a single file with plain csc, so source generators do not run there. This example is deliberately broken to show what you see without the generator.

C# Without the generator (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The equivalent hand-written code works everywhere. Keep a static readonly field and the same options, and switch to the attribute in your real project.

C# Hand-written equivalent

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Usage in a normal project, read-only:

C#
using System.Text.RegularExpressions;

public partial class Validator
{
    [GeneratedRegex(@"^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$",
        RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 500)]
    private static partial Regex Email();

    public static bool IsEmail(string s) => Email().IsMatch(s);

    // Since .NET 9 / C# 13: a partial property
    [GeneratedRegex(@"\d+")]
    private static partial Regex Digits { get; }
}

Syntax

C#
[GeneratedRegex(string pattern)]
[GeneratedRegex(string pattern, RegexOptions options)]
[GeneratedRegex(string pattern, RegexOptions options, int matchTimeoutMilliseconds)]
[GeneratedRegex(string pattern, RegexOptions options, string cultureName)]
[GeneratedRegex(string pattern, RegexOptions options, int matchTimeoutMilliseconds, string cultureName)]
Argument Description
pattern A constant string. It is parsed at build time.
options RegexOptions. Compiled is accepted but unnecessary; NonBacktracking is not supported by the generator.
matchTimeoutMilliseconds Match timeout. Omit it for no timeout.
cultureName Culture used with IgnoreCase, such as "en-US".

Returns: the annotated partial method or property returns a cached Regex instance; calling it repeatedly returns the same object.

Errors / undefined behavior: an invalid pattern is a compile-time error with a diagnostic, not a run-time exception. The attribute needs a partial member in a partial type, otherwise the generator reports a diagnostic.

Usage notes

  • Why the one-file runner fails. The generator never ran, so the partial method has no body, and the compiler reports error CS8795: Partial method 'Patterns.ZipCode()' must have an implementation part because it has accessibility modifiers. If you ever see CS8795 in a real project, check that the project references the .NET SDK version that ships the generator and that the type is partial.
  • Requirements. .NET 7 or later, partial containing types (nested types too), and the member must be non-generic with no parameters. Method form works on C# 11; the property form needs C# 13 and .NET 9.
  • Prefer it to RegexOptions.Compiled for patterns known at build time: no startup cost for IL generation, and AOT-friendly.
  • The pattern must be a constant. For patterns built at run time you still need new Regex(...).
  • Analyzer help. Rule SYSLIB1045 suggests converting static calls and new Regex("literal") fields to [GeneratedRegex], with a code fix.
  • Inspect the output. In Visual Studio or Rider, "Go to definition" on the method opens the generated code, which contains comments describing the pattern. It is useful for debugging performance.
  • Same semantics. Matching results are the same as the interpreter, including groups and replacement; only NonBacktracking differs.
  • Thread safety. The returned Regex is immutable and shared across threads.