The Regex class in System.Text.RegularExpressions finds patterns in text: dates in a log line, order numbers in an email, repeated whitespace you want to collapse. Below are the calls you will use most, the .NET-specific traps, and a syntax reference at the end.
Match, extract, replace and split
using System.Text.RegularExpressions;
string text = "Order 1042 shipped on 2024-03-15, order 1043 on 2024-03-18.";
// Is there a match at all?
bool hasDate = Regex.IsMatch(text, @"\d{4}-\d{2}-\d{2}");
Console.WriteLine(hasDate);
// True
// First match, read through named groups
Match date = Regex.Match(text, @"(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})");
if (date.Success)
{
Console.WriteLine(date.Groups["month"].Value);
}
// 03
// Every match
foreach (Match order in Regex.Matches(text, @"order (\d+)", RegexOptions.IgnoreCase))
{
Console.WriteLine(order.Groups[1].Value);
}
// 1042
// 1043
// Replace, reusing captured groups
Console.WriteLine(Regex.Replace(text, @"(\d{4})-(\d{2})-(\d{2})", "$3.$2.$1"));
// Order 1042 shipped on 15.03.2024, order 1043 on 18.03.2024.
// Split on any run of commas, semicolons or whitespace
string[] parts = Regex.Split("one, two;three four", @"[,;\s]+");
Console.WriteLine(string.Join(" | ", parts));
// one | two | three | four
Write patterns as verbatim strings (@"..."). In a normal string literal, "\d" does not compile and "\b" silently becomes a backspace character, so you would have to double every backslash.
Groups[0] is always the whole match; numbered groups start at 1. Named groups ((?<year>...)) keep working when someone later adds another group to the pattern, so prefer them for anything you will maintain.
Use source-generated regex on .NET 7 and later
When a pattern is known at compile time, let the compiler generate the matching code:
using System.Text.RegularExpressions;
string text = "Shipped on 2024-03-15.";
Match m = Patterns.IsoDate().Match(text);
Console.WriteLine(m.Groups["year"].Value);
// 2024
static partial class Patterns
{
[GeneratedRegex(@"(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})")]
public static partial Regex IsoDate();
}
The [GeneratedRegex] attribute makes a source generator emit plain C# for the pattern at build time. You skip the parsing and compilation cost at startup, the generated code works with trimming and Native AOT, and you can step into it in the debugger to see what the pattern actually does. An invalid pattern becomes a build error instead of a runtime ArgumentException. On .NET 9 (C# 13) the attribute also works on a static partial Regex property.
On older targets, create the Regex once and keep it in a static readonly field, with RegexOptions.Compiled if it runs in a hot path. The static helpers like Regex.IsMatch(input, pattern) are fine for occasional calls: they cache the 15 most recently used patterns (Regex.CacheSize), but a busy app with many patterns will thrash that cache.
Traps specific to .NET
\d and \w are Unicode-aware. \d matches any Unicode decimal digit, including Arabic-Indic ٣ or full-width 3, and \w matches letters from every script. That is usually what you want for words, but not for validating an ID that later goes through int.Parse or a database column. Use [0-9] and [A-Za-z0-9_] when you mean ASCII, or pass RegexOptions.ECMAScript.
$ also matches before a final newline. ^\d+$ accepts "123\n". Use \z when the string must end right there; this matters for validation.
Catastrophic backtracking. Nested quantifiers such as (a+)+ or ([-.\w]*[a-z])* can take exponential time on input that almost matches. If the pattern runs on user input, pass a timeout so a bad string throws RegexMatchTimeoutException instead of pinning a CPU core:
var regex = new Regex(@"^(\w+\s?)+$", RegexOptions.None, TimeSpan.FromMilliseconds(200));
Since .NET 7 you can also use RegexOptions.NonBacktracking, which guarantees linear time at the cost of a few features (no lookarounds, no backreferences, no atomic groups).
Culture and case. RegexOptions.IgnoreCase uses the casing table of the current culture by default. Add RegexOptions.CultureInvariant for patterns that process identifiers or protocol text, so a Turkish machine treats i and I the same way yours does.
Syntax cheat sheet
| Pattern | Meaning |
|---|---|
\ | Escapes the next character: \. matches a literal dot, \( a parenthesis. |
. | Any character except \n (with RegexOptions.Singleline, any character). |
^ | Start of the string; start of each line with RegexOptions.Multiline. |
$ | End of the string or before a final \n; end of each line with Multiline. |
\A | Start of the string only, regardless of Multiline. |
\z | End of the string only. |
\Z | End of the string or before a final \n, regardless of Multiline. |
\G | The position where the previous match ended. |
* | Zero or more times: zo* matches z and zoo. |
+ | One or more times: zo+ matches zoo but not z. |
? | Zero or one time: colou?r matches color and colour. |
{n} | Exactly n times: o{2} matches the oo in food but nothing in Bob. |
{n,} | At least n times. |
{n,m} | Between n and m times. |
*?, +?, ?? | Lazy versions: match as little as possible. <.+?> matches <b> in <b>bold</b>, while <.+> matches the whole string. |
[abc] | Any one of the listed characters. |
[^abc] | Any character except those listed. |
[a-z] | Any character in the range. |
\d / \D | A Unicode decimal digit / anything else. |
\w / \W | A word character (Unicode letters, digits, underscore) / anything else. |
\s / \S | Whitespace, including tab, newlines and Unicode spaces / anything else. |
\b / \B | A word boundary / not a word boundary: er\b matches the er in never but not in verb. |
\t, \n, \r | Tab, line feed, carriage return. |
\x41, A | A character by hex code (exactly 2 or 4 hex digits); both match A. |
(pattern) | Capturing group, available as Groups[1], Groups[2] and so on. |
(?<name>pattern) | Named capturing group, available as Groups["name"]. |
(?:pattern) | Non-capturing group: groups without storing the match. |
\1, \k<name> | Backreference: (\w)\1 matches a doubled letter such as ll. |
(?=...) / (?!...) | Positive / negative lookahead: \d+(?= EUR) matches 25 in 25 EUR. |
(?<=...) / (?<!...) | Positive / negative lookbehind: (?<=\$)\d+ matches 25 in $25. |
Alternation uses the vertical bar: cat|dog matches either word, and (z|w)oo matches zoo or woo. Alternation has the lowest precedence, so ^cat|dog$ means “starts with cat, or ends with dog”. Wrap it in a group when you mean something else: ^(cat|dog)$.
The full reference is on Microsoft Learn: Regular expression language quick reference.