Regex in C#: Match, Replace and Groups (with Source-Generated Regex)

For a C# regex match, call Regex.Match(input, pattern), check .Success, then read .Value and .Index:

#:property PublishAot=false
using System.Text.RegularExpressions;

string input = "Call Jenna at (555) 010-2026 after 3 PM.";
Match m = Regex.Match(input, @"\d{3}-\d{4}");
if (m.Success)
    Console.WriteLine($"{m.Value} at index {m.Index}");
010-2026 at index 20

Quick answer: Match returns the first hit, Matches returns all of them, and IsMatch only says yes or no. A failed match never returns null, so Success is the check that matters.

Every pattern below ran on .NET 10 against US phone numbers, ZIP codes and addresses, ending with a benchmark of five ways to run the same regex.

Regex.IsMatch vs Regex.Match: Which One Do You Need?

Use IsMatch when you only need true or false, such as validating a form field. It stops at the first hit and never builds a Match object. Here’s a ZIP code check with and without anchors:

#:property PublishAot=false
using System.Text.RegularExpressions;

string[] zips = ["98101", "98101-1234", "9810", "Seattle, WA 98101"];

foreach (string zip in zips)
{
    bool exact = Regex.IsMatch(zip, @"^\d{5}(-\d{4})?$");
    bool contains = Regex.IsMatch(zip, @"\d{5}");
    Console.WriteLine($"{zip,-18} exact={exact,-6} contains={contains}");
}

Output:

98101              exact=True   contains=True
98101-1234         exact=True   contains=True
9810               exact=False  contains=False
Seattle, WA 98101  exact=False  contains=True

Without ^ and $, Seattle, WA 98101 passed as a ZIP code, because the pattern only has to appear somewhere. For validation, always anchor both ends.

For a plain substring test, string.Contains is simpler and faster than any regex. Every demo here is a .NET 10 file-based app you can paste and run with dotnet run.

Find Every Match with Regex.Matches and NextMatch

Same idea, but a shipping note with three ZIP codes in it. Regex.Matches returns a MatchCollection, and NextMatch() walks the hits one at a time:

#:property PublishAot=false
using System.Text.RegularExpressions;

string notes = "Ship to WA 98101, OR 97205-4410 and CA 94105.";

MatchCollection zips = Regex.Matches(notes, @"\b\d{5}(?:-\d{4})?\b");
Console.WriteLine($"Found {zips.Count} ZIP codes");
foreach (Match zip in zips)
    Console.WriteLine($"  {zip.Value} at index {zip.Index}");

List<string> list = zips.Select(z => z.Value).ToList();
Console.WriteLine(string.Join(" | ", list));

Match state = Regex.Match(notes, @"\b[A-Z]{2}\b");
while (state.Success)
{
    Console.Write(state.Value + " ");
    state = state.NextMatch();
}

Output:

Found 3 ZIP codes
  98101 at index 11
  97205-4410 at index 21
  94105 at index 39
98101 | 97205-4410 | 94105
WA OR CA
C# Regex.Matches loop finding three US ZIP codes in a shipping note, converting the matches to a List and walking state codes with NextMatch, in VS Code
Regex.Matches found 3 ZIP codes; NextMatch walked WA, OR and CA

It found 3 ZIP codes, including the ZIP+4 97205-4410. (?:...) groups without capturing, and \b stops a 9-digit number from matching halfway.

MatchCollection implements IEnumerable<Match>, so LINQ turns it into a list or array in one line. From there, joining the list into a comma-separated string is one more call.

Regex Groups in C#: Numbered and Named Groups

Parentheses capture part of a match. Groups[0] is the whole match and Groups[1] is the first (...). Named groups, (?<zip>\d{5}), are easier to read once there are more than two:

#:property PublishAot=false
using System.Text.RegularExpressions;

Match p = Regex.Match("(555) 010-2026", @"\((\d{3})\) (\d{3})-(\d{4})");
Console.WriteLine($"Area code {p.Groups[1].Value}, line {p.Groups[3].Value}");

var address = new Regex(@"(?<city>[A-Za-z][A-Za-z ]*),\s (?<state>[A-Z]{2})\s
    (?<zip>\d{5}) (-(?<plus4>\d{4}))? $", RegexOptions.IgnorePatternWhitespace);
Match m = address.Match("Jenna Morales, 1420 Pine St, Seattle, WA 98101-1234");

Console.WriteLine($"City:  {m.Groups["city"].Value}");
Console.WriteLine($"State: {m.Groups["state"].Value}");
Console.WriteLine($"ZIP:   {m.Groups["zip"].Value} + {m.Groups["plus4"].Value}");
Console.WriteLine($"Groups[1]: {m.Groups[1].Value}");

Output:

Area code 555, line 2026
City:  Seattle
State: WA
ZIP:   98101 + 1234
Groups[1]: -1234
C# regex named groups city, state, zip and plus4 parsing a Seattle WA ZIP+4 address, plus numbered groups on a US phone number, in VS Code
Named groups pull the city, state and ZIP+4 out of one address line

Look at the last line: Groups[1]: -1234. Unnamed groups are numbered first and named groups after them, so mixing both makes the numbers surprising. I read named groups by name only.

Keep the captured ZIP as a string. A Boston ZIP like 02108 loses its zero as an int, and you’d have to add the leading zeros back.

Note: RegexOptions.IgnorePatternWhitespace let me split the pattern over two lines. It ignores spaces in the pattern, except inside [...], so \s matches the real spaces.

Groups vs Captures

When a group repeats, Group.Value keeps only the last repetition. Captures keeps all of them:

#:property PublishAot=false
using System.Text.RegularExpressions;

Match m = Regex.Match("WA,OR,CA,NV", @"^(?:(?<st>[A-Z]{2}),?)+$");

Console.WriteLine($"Group value: {m.Groups["st"].Value}");
foreach (Capture cap in m.Groups["st"].Captures)
    Console.Write(cap.Value + " ");

Output:

Group value: NV
WA OR CA NV

The group’s value is NV, but its Captures hold all four states.

Regex.Replace with $1, ${name} and a MatchEvaluator

Regex.Replace can reuse what the groups captured. $1 inserts group 1, ${name} inserts a named group, and a lambda (a MatchEvaluator) builds each replacement in code:

#:property PublishAot=false
using System.Text.RegularExpressions;

string raw = "Jenna: 5550102026, Tyler: 555.010.7788";

// $1, $2, $3 = numbered groups
Console.WriteLine(Regex.Replace(raw, @"(\d{3})\.?(\d{3})\.?(\d{4})", "($1) $2-$3"));

// ${name} = named groups
Console.WriteLine(Regex.Replace("Due 2026-12-03", @"(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})",
    "${m}/${d}/${y}"));

// MatchEvaluator = compute each replacement in code
string emails = "jenna.morales@example.com, tyler@example.com";
Console.WriteLine(Regex.Replace(emails, @"\b(\w)[\w.]*@",
    m => m.Groups[1].Value + "***@"));

Output:

Jenna: (555) 010-2026, Tyler: (555) 010-7788
Due 12/03/2026
j***@example.com, t***@example.com
C# Regex.Replace formatting US phone numbers with $1 $2 $3, reordering a date with ${name} substitutions and masking emails with a MatchEvaluator, in VS Code
Numbered, named and MatchEvaluator replacements on the same kind of data

Both phone formats became (555) 010-2026, and the ISO date turned into US order. To format a real date, parse it and use DateTime format strings instead.

string.Replace is the faster pick when the text to find is fixed. For stripping symbols, I wrote a full guide to removing special characters from a string.

Split a String with Regex.Split

I reach for this when a user types a list of states however they like. string.Split needs exact separators. Regex.Split takes a pattern, so mixed commas, semicolons, pipes and spaces are one call:

#:property PublishAot=false
using System.Text.RegularExpressions;

string states = "WA, OR;CA  NV|AZ";
string[] parts = Regex.Split(states, @"[,;|\s]+");
Console.WriteLine($"{parts.Length} items: {string.Join(" / ", parts)}");

string[] zipParts = Regex.Split("98101-1234", @"(-)");
Console.WriteLine(string.Join(" / ", zipParts));

Output:

5 items: WA / OR / CA / NV / AZ
98101 / - / 1234

That gave 5 items. A capture group in the pattern keeps the separator in the result, which is why the hyphen shows up on the second line.

Once you’ve got the array, checking whether it contains a specific state is a single call.

RegexOptions: IgnoreCase, Multiline, Compiled and NonBacktracking

Options change how the engine reads the pattern. You’ll see the difference fastest on the same three order lines, run three ways:

#:property PublishAot=false
using System.Text.RegularExpressions;

string orders = """
    order 1001 shipped to WA
    Order 1002 pending in OR
    ORDER 1003 shipped to CA
    """;
string pattern = @"^order \d+";

Console.WriteLine(Regex.Matches(orders, pattern).Count);
Console.WriteLine(Regex.Matches(orders, pattern, RegexOptions.IgnoreCase).Count);
Console.WriteLine(Regex.Matches(orders, pattern,
    RegexOptions.IgnoreCase | RegexOptions.Multiline).Count);

Output:

1
1
3

Plain ^ means start of the whole string, so it found 1. IgnoreCase alone still found 1; adding Multiline makes ^ match at every line, giving 3.

OptionWhat it doesWhen I use it
IgnoreCaseCase-insensitive matchUser input, state names
Multiline^ and $ match at each lineLog files, pasted lists
Singleline. also matches \nMulti-line blocks
IgnorePatternWhitespaceSpaces and # comments in the patternLong patterns
CompiledCompiles to IL; slower start, faster runsHot paths on older .NET
NonBacktrackingLinear time, no backtracking (.NET 7+)Untrusted input
CultureInvariantIgnores culture differences in caseWith IgnoreCase

Set a Regex Match Timeout (RegexMatchTimeoutException)

A badly nested pattern can backtrack for seconds or minutes on the wrong input. The default timeout is Regex.InfiniteMatchTimeout, so nothing stops it unless you pass a TimeSpan:

#:property PublishAot=false
using System.Text.RegularExpressions;
using System.Diagnostics;

string input = new string('a', 32) + "!";

var risky = new Regex(@"^(\w+\s?)+$", RegexOptions.None, TimeSpan.FromMilliseconds(250));
try
{
    Console.WriteLine(risky.IsMatch(input));
}
catch (RegexMatchTimeoutException ex)
{
    Console.WriteLine($"Timed out after {ex.MatchTimeout.TotalMilliseconds} ms");
}

var safe = new Regex(@"^(\w+\s?)+$", RegexOptions.NonBacktracking);
var sw = Stopwatch.StartNew();
Console.WriteLine($"NonBacktracking: {safe.IsMatch(input)} in {sw.ElapsedMilliseconds} ms");

Output:

Timed out after 250 ms
NonBacktracking: False in 10 ms
C# Regex with a 250 ms match timeout throwing RegexMatchTimeoutException on a catastrophic backtracking pattern, and RegexOptions.NonBacktracking returning in milliseconds, in VS Code
The backtracking engine gave up at 250 ms; NonBacktracking answered right away

32 letters and a ! were enough to blow the 250 ms budget. NonBacktracking answered False in about 10 ms on my run, because its run time grows linearly with the input.

Catch RegexMatchTimeoutException with a normal try-catch and treat it as invalid input. You can also set an app-wide default with AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT", ...).

Source-Generated Regex with [GeneratedRegex] (.NET 7+)

[GeneratedRegex] makes the compiler write the matching code at build time. It goes on a static partial method (.NET 7+) or a partial property (.NET 9+, C# 13):

#:property PublishAot=false
using System.Text.RegularExpressions;

string[] inputs = ["(555) 010-2026", "Seattle, WA 98101", "555-0102"];
foreach (string s in inputs)
    Console.WriteLine($"{s,-18} phone={Patterns.UsPhone.IsMatch(s),-6} zip={Patterns.Zip().IsMatch(s)}");

static partial class Patterns
{
    // .NET 9+ / C# 13: partial property
    [GeneratedRegex(@"^\(\d{3}\) \d{3}-\d{4}$")]
    public static partial Regex UsPhone { get; }

    // .NET 7+: partial method, with a match timeout
    [GeneratedRegex(@"\b\d{5}\b", RegexOptions.None, matchTimeoutMilliseconds: 100)]
    public static partial Regex Zip();
}

Output:

(555) 010-2026     phone=True   zip=False
Seattle, WA 98101  phone=False  zip=True
555-0102           phone=False  zip=False
C# [GeneratedRegex] on a static partial property for US phone numbers and a partial method with a match timeout for ZIP codes, with dotnet run output in VS Code
One partial property, one partial method, both written by the source generator

The inputs are a collection expression, and the generated code caches a single instance, so there’s no static field to manage. The attribute also takes options, a timeout and a culture name, like the Zip() method above.

Pro Tip: when a pattern is a constant, the SYSLIB1045 analyzer suggests switching to [GeneratedRegex], and the code fix converts it for you. The generator ignores RegexOptions.Compiled, and NonBacktracking falls back to a cached normal Regex.

Allocation-Free Matching with EnumerateMatches and ValueMatch

Regex.EnumerateMatches (.NET 7+) works on a ReadOnlySpan<char> and yields ValueMatch structs with only Index and Length. No Match objects and no substrings are created:

#:property PublishAot=false
using System.Text.RegularExpressions;

ReadOnlySpan<char> log = "WA 98101; OR 97205; CA 94105-1200; TX 73301";

foreach (ValueMatch vm in Regex.EnumerateMatches(log, @"\b\d{5}\b"))
    Console.WriteLine($"{log.Slice(vm.Index, vm.Length)} at index {vm.Index}");

Console.WriteLine($"States: {Regex.Count(log, @"\b[A-Z]{2}\b")}");

Output:

98101 at index 3
97205 at index 13
94105 at index 23
73301 at index 38
States: 4

It found all four ZIP codes, and Regex.Count counted 4 state codes without allocating a collection. Slice the span only when you need the text.

How Fast Is Each Way? new Regex vs Static vs Compiled vs [GeneratedRegex]

I ran BenchmarkDotNet 0.15.8 (ShortRun, in-process) on one dev desktop with .NET 10. Each method checks the same shipping line for a ZIP code:

#:package BenchmarkDotNet@0.15.8
#:property PublishAot=false
#:property Optimize=true
using System.Text.RegularExpressions;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
using BenchmarkDotNet.Toolchains.InProcess.Emit;

var job = Job.ShortRun.WithToolchain(InProcessEmitToolchain.Instance);
BenchmarkRunner.Run<ZipBench>(DefaultConfig.Instance.AddJob(job));

[MemoryDiagnoser]
public partial class ZipBench
{
    const string Input = "Ship to Seattle, WA 98101-1234 by 12/03/2026";
    const string Pattern = @"\b\d{5}(-\d{4})?\b";
    static readonly Regex Cached = new(Pattern);
    static readonly Regex Compiled = new(Pattern, RegexOptions.Compiled);

    [Benchmark(Baseline = true)]
    public bool NewRegexEachCall() => new Regex(Pattern).IsMatch(Input);

    [Benchmark] public bool StaticIsMatch() => Regex.IsMatch(Input, Pattern);
    [Benchmark] public bool CachedInstance() => Cached.IsMatch(Input);
    [Benchmark] public bool CompiledOption() => Compiled.IsMatch(Input);
    [Benchmark] public bool SourceGenerated() => Zip.IsMatch(Input);

    [GeneratedRegex(Pattern)]
    private static partial Regex Zip { get; }
}
MethodMeanRatioAllocated
NewRegexEachCall2,177.62 ns1.004104 B
StaticIsMatch133.84 ns0.06–
CachedInstance131.99 ns0.06–
CompiledOption60.79 ns0.03–
SourceGenerated45.52 ns0.02–

Building a new Regex on every call was by far the slowest (2,177.62 ns). The source-generated regex took 45.52 ns and the compiled one 60.79 ns.

The static Regex.IsMatch (133.84 ns) matched a cached instance (131.99 ns) because .NET caches the last 15 static patterns. These numbers come from one machine; the ratios matter more than the nanoseconds.

C# Regex Cheat Sheet

Each row is a real Regex.Match from the program below, which printed the pattern, the input and the matched text:

PatternMeaningInputMatch
\d{5}exactly 5 digitsSeattle, WA 9810198101
\d{5}(-\d{4})?ZIP or ZIP+498101-123498101-1234
\(\d{3}\) \d{3}-\d{4}US phone, escaped ( )Call (555) 010-2026(555) 010-2026
\b[A-Z]{2}\bwhole-word 2 capitalsAustin, TX 73301TX
^Orderstarts withOrder 1001 shippedOrder
shipped$ends withOrder 1001 shippedshipped
[\w.]+@example\.comemail at one domainjenna.morales@example.comjenna.morales@example.com
\$\d+\.\d{2}dollar amountTotal: $149.99$149.99
(?i)seattleinline ignore caseSEATTLE, WASEATTLE
WA|OR|CAalternation (or)Ships from OROR
\d+(?= items)lookaheadPacked 12 items12
(?<=#)\d+lookbehindTicket #45214521
\s+one or more spacesTyler Brooks3 spaces
[^0-9]+anything but digits555-0102-
#:property PublishAot=false
using System.Text.RegularExpressions;

(string Pattern, string Input)[] rows =
[
    (@"\d{5}", "Seattle, WA 98101"),
    (@"\d{5}(-\d{4})?", "98101-1234"),
    (@"\(\d{3}\) \d{3}-\d{4}", "Call (555) 010-2026"),
    (@"\b[A-Z]{2}\b", "Austin, TX 73301"),
    (@"^Order", "Order 1001 shipped"),
    (@"shipped$", "Order 1001 shipped"),
    (@"[\w.]+@example\.com", "jenna.morales@example.com"),
    (@"\$\d+\.\d{2}", "Total: $149.99"),
    (@"(?i)seattle", "SEATTLE, WA"),
    (@"WA|OR|CA", "Ships from OR"),
    (@"\d+(?= items)", "Packed 12 items"),
    (@"(?<=#)\d+", "Ticket #4521"),
    (@"\s+", "Tyler   Brooks"),
    (@"[^0-9]+", "555-0102"),
];

foreach (var (pattern, input) in rows)
    Console.WriteLine($"{pattern}\t{input}\t[{Regex.Match(input, pattern).Value}]");

Common Regex Errors and How to Fix Them

ProblemWhyFix
CS1009: unrecognized escape sequence"\d" in a normal stringVerbatim @"\d" or a raw string
Validation accepts extra textNo anchorsWrap the pattern in ^...$
Groups[1] has the wrong textUnnamed groups are numbered firstRead named groups by name
RegexParseExceptionUnbalanced ( or [Escape literal \( \[
App hangs on some inputCatastrophic backtrackingTimeout or NonBacktracking
ArgumentNullExceptionInput is nullGuard with string.IsNullOrEmpty

For the null case, the checks in checking if a string is null or empty come before any regex call.

Which Regex API Should You Pick?

  • Yes/no validation: IsMatch with ^...$.
  • First hit or groups: Match, then Groups["name"].
  • All hits: Matches, or EnumerateMatches in hot paths.
  • Any pattern known at compile time: [GeneratedRegex].
  • Input from users or files: a match timeout, or NonBacktracking.

More string and .NET recipes are on my C# tutorials page.

If you work with text a lot, these string posts pair well with regex:

Frequently Asked Questions

What’s the difference between Regex.Match and Regex.Matches in C#?

Match returns the first match only (check Success). Matches returns a MatchCollection with every non-overlapping match, which you can loop or convert to a list with LINQ.

How do I get a named group value from a regex match?

Name the group with (?<zip>\d{5}) and read match.Groups["zip"].Value. If the group didn’t take part in the match, Value is an empty string, not null.

How do I use a regex OR condition in C#?

Use the | alternation operator, for example WA|OR|CA. Wrap it in a group, ^(WA|OR|CA)$, when it’s only part of a longer pattern.

Is Regex.Replace slower than string.Replace?

Yes, for fixed text. Use string.Replace when you know the exact text, and Regex.Replace when you need a pattern, group substitutions or a MatchEvaluator.

Should I use [GeneratedRegex] or RegexOptions.Compiled?

Use [GeneratedRegex] whenever the pattern is known at compile time (.NET 7+). Microsoft’s regex source generator guide recommends it over Compiled.

Does C# regex have a default timeout?

No. The default is Regex.InfiniteMatchTimeout. Pass a TimeSpan to the constructor or set REGEX_DEFAULT_MATCH_TIMEOUT, as the regex best practices page explains.