Regex tester · Guide

Regex Tester C#: Testing .NET Regular Expressions

.NET has one of the most capable regex engines available — balancing groups, variable-length lookbehind, right-to-left matching. That power comes with performance characteristics worth understanding before you ship a pattern.

Verbatim strings

Prefix the literal with @ and backslashes stop needing escapes, so the pattern in your code matches the pattern in the tester exactly:

C#
var re = new Regex(@"\d{4}-\d{2}-\d{2}");   // readable
var bad = new Regex("\\d{4}-\\d{2}");        // works, harder to read

Use @ always for regex. The only wrinkle is that a double quote inside a verbatim string is written "".

Options

C#
RegexOptions.IgnoreCase        // (?i)
RegexOptions.Singleline        // (?s) — dot matches newline
RegexOptions.Multiline         // (?m) — ^ and $ per line
RegexOptions.IgnorePatternWhitespace  // (?x) — comments in patterns
RegexOptions.Compiled          // compile to IL for hot paths

Note the naming trap: Singleline is what other languages call dotall, and Multiline changes anchors. They are independent and frequently confused because the names suggest the opposite of what they do.

Named groups and the source generator

Named groups use (?<name>...) and read as m.Groups["name"].Value. Since .NET 7, the source generator produces a compiled matcher at build time with no startup cost:

C#
public partial class Parser
{
    [GeneratedRegex(@"(?<year>\d{4})-(?<month>\d{2})", RegexOptions.IgnoreCase)]
    private static partial Regex DateRegex();
}

var m = Parser.DateRegex().Match(input);
if (m.Success) { var year = m.Groups["year"].Value; }

Prefer [GeneratedRegex] over RegexOptions.Compiled in new code — same speed, no runtime IL emission, and the pattern is validated at compile time.

Always set a timeout

.NET regex backtracks, and a pathological pattern against hostile input can run effectively forever. Unlike most engines, .NET lets you bound it:

C#
var re = new Regex(pattern, RegexOptions.None, TimeSpan.FromMilliseconds(200));

Do this for any pattern touching user input. It converts a denial-of-service into a catchable RegexMatchTimeoutException.

Frequently asked questions

What does RegexOptions.Singleline do?

It makes the dot match newlines — what other languages call dotall. It does not affect anchors.

Compiled or GeneratedRegex?

GeneratedRegex on .NET 7+. It gives the same performance with no runtime code generation.

Why should I set a regex timeout?

Catastrophic backtracking on untrusted input can hang a thread. A timeout turns it into an exception you can handle.

Ready to try it?

Open the free browser-based Regex tester and apply what you just read — no sign-up, runs locally.

Open the Regex tester tool