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

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

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

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.
| Option | What it does | When I use it |
|---|---|---|
IgnoreCase | Case-insensitive match | User input, state names |
Multiline | ^ and $ match at each line | Log files, pasted lists |
Singleline | . also matches \n | Multi-line blocks |
IgnorePatternWhitespace | Spaces and # comments in the pattern | Long patterns |
Compiled | Compiles to IL; slower start, faster runs | Hot paths on older .NET |
NonBacktracking | Linear time, no backtracking (.NET 7+) | Untrusted input |
CultureInvariant | Ignores culture differences in case | With 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

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](https://aspdotnethelp.com/wp-content/uploads/2026/11/csharp-generatedregex-partial-property-and-method.png)
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; }
}
| Method | Mean | Ratio | Allocated |
|---|---|---|---|
NewRegexEachCall | 2,177.62 ns | 1.00 | 4104 B |
StaticIsMatch | 133.84 ns | 0.06 | – |
CachedInstance | 131.99 ns | 0.06 | – |
CompiledOption | 60.79 ns | 0.03 | – |
SourceGenerated | 45.52 ns | 0.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:
| Pattern | Meaning | Input | Match |
|---|---|---|---|
\d{5} | exactly 5 digits | Seattle, WA 98101 | 98101 |
\d{5}(-\d{4})? | ZIP or ZIP+4 | 98101-1234 | 98101-1234 |
\(\d{3}\) \d{3}-\d{4} | US phone, escaped ( ) | Call (555) 010-2026 | (555) 010-2026 |
\b[A-Z]{2}\b | whole-word 2 capitals | Austin, TX 73301 | TX |
^Order | starts with | Order 1001 shipped | Order |
shipped$ | ends with | Order 1001 shipped | shipped |
[\w.]+@example\.com | email at one domain | jenna.morales@example.com | jenna.morales@example.com |
\$\d+\.\d{2} | dollar amount | Total: $149.99 | $149.99 |
(?i)seattle | inline ignore case | SEATTLE, WA | SEATTLE |
WA|OR|CA | alternation (or) | Ships from OR | OR |
\d+(?= items) | lookahead | Packed 12 items | 12 |
(?<=#)\d+ | lookbehind | Ticket #4521 | 4521 |
\s+ | one or more spaces | Tyler Brooks | 3 spaces |
[^0-9]+ | anything but digits | 555-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
| Problem | Why | Fix |
|---|---|---|
| CS1009: unrecognized escape sequence | "\d" in a normal string | Verbatim @"\d" or a raw string |
| Validation accepts extra text | No anchors | Wrap the pattern in ^...$ |
Groups[1] has the wrong text | Unnamed groups are numbered first | Read named groups by name |
RegexParseException | Unbalanced ( or [ | Escape literal \( \[ |
| App hangs on some input | Catastrophic backtracking | Timeout or NonBacktracking |
ArgumentNullException | Input is null | Guard 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:
IsMatchwith^...$. - First hit or groups:
Match, thenGroups["name"]. - All hits:
Matches, orEnumerateMatchesin 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:
- Remove a particular character from a string in C#
- Compare a string with multiple values
- Get the first N characters of a string
- String vs StringBuilder in C#
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.
Bijay Kumar is a renowned software engineer, accomplished author, and distinguished Microsoft Most Valuable Professional (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. Read more…