C# Regular Expressions
last modified November 15, 2026
This article shows how to search, validate, replace, and split text in C# with regular expressions.
Regular expressions are patterns that describe sets of strings. They are
used for searching, validating, and transforming text in tools such as
grep and sed, in text editors, and in most
programming languages.
In .NET, regular expressions live in the
System.Text.RegularExpressions namespace. Its central type is
the Regex class, an immutable, thread-safe representation of a
pattern. It has instance methods and static counterparts for the most common
operations:
IsMatchtests whether the pattern occurs in the input,Match,Matches, andCountfind the occurrences,Replacesubstitutes them with other text,Splitsplits the input at the occurrences.
The static methods cache the most recently used patterns, so calling them
repeatedly with the same pattern does not parse it each time. Patterns are
usually written as verbatim strings (@"\d+") so that the
backslashes need no escaping.
Regex syntax
The following table lists commonly used elements of the pattern syntax.
| Regex | Meaning |
|---|---|
. |
Matches any single character except a newline. |
? |
Matches the preceding element zero or one time. |
+ |
Matches the preceding element one or more times. |
* |
Matches the preceding element zero or more times. |
{n,m} |
Matches the preceding element at least n and at most m times. |
^ |
Matches the start of the string (of a line in multiline mode). |
$ |
Matches the end of the string (of a line in multiline mode). |
\b |
Matches a word boundary. |
| |
Alternation; matches either the left or the right side. |
(...) |
Capturing group. |
[abc] |
Matches a, b, or c. |
[a-c] |
Range; matches a, b, or c. |
[^abc] |
Negation; matches any character except a, b, or c. |
\d |
Matches a Unicode decimal digit. |
\s |
Matches a white space character. |
\w |
Matches a word character: a Unicode letter, digit, or connector such as the underscore. |
C# regex IsMatch
The IsMatch method indicates whether the regular expression
finds a match in the input string.
using System.Text.RegularExpressions;
string[] words = ["Seven", "even", "Maven", "Amen", "eleven"];
var rx = new Regex(".even");
foreach (string word in words)
{
if (rx.IsMatch(word))
{
Console.WriteLine($"{word} does match");
}
else
{
Console.WriteLine($"{word} does not match");
}
}
We check which words of an array match the .even pattern.
var rx = new Regex(".even");
The dot metacharacter stands for any single character, so the pattern matches the text "even" preceded by one more character. The match can occur anywhere in the input.
if (rx.IsMatch(word))
IsMatch returns true if the pattern occurs in the
word. "even" does not match because there is no character before it; "Maven"
does not match because it contains "aven", not "even".
$ dotnet run Seven does match even does not match Maven does not match Amen does not match eleven does match
C# regex Match and NextMatch
The Match method returns the first occurrence of the pattern as
a Match object. Its Success property tells whether
a match was found, Value holds the matched text, and
Index its position. NextMatch continues the search
where the previous match ended.
using System.Text.RegularExpressions;
string content = """
Foxes are omnivorous mammals belonging to several genera
of the family Canidae. Foxes have a flattened skull, upright triangular ears,
a pointed, slightly upturned snout, and a long bushy tail. Foxes live on every
continent except Antarctica. By far the most common and widespread species of
fox is the red fox.
""";
var rx = new Regex("fox(es)?", RegexOptions.IgnoreCase);
Match match = rx.Match(content);
while (match.Success)
{
Console.WriteLine($"{match.Value} at index {match.Index}");
match = match.NextMatch();
}
We look for all occurrences of the word fox in a text.
var rx = new Regex("fox(es)?", RegexOptions.IgnoreCase);
The (es)? part makes the plural ending optional.
RegexOptions.IgnoreCase enables case-insensitive matching, so
"Foxes" at the start of a sentence is found too.
while (match.Success)
{
Console.WriteLine($"{match.Value} at index {match.Index}");
match = match.NextMatch();
}
We loop until a match fails. The text is a raw string literal whose indentation is removed by the compiler, so the indexes count from the first letter of "Foxes".
$ dotnet run Foxes at index 0 Foxes at index 80 Foxes at index 194 fox at index 292 fox at index 307
C# regex Matches
The Matches method returns all occurrences of the pattern in a
MatchCollection. If there are no matches, the collection is
empty.
using System.Text.RegularExpressions;
string content = """
<p>The <code>Regex</code> class represents an immutable
regular expression.</p>
""";
var rx = new Regex("</?[a-z]+>");
MatchCollection matches = rx.Matches(content);
Console.WriteLine($"Found {matches.Count} tags");
foreach (Match match in matches)
{
Console.WriteLine($"{match.Value} at {match.Index}");
}
The example finds the HTML tags in a string.
var rx = new Regex("</?[a-z]+>");
The pattern matches an opening angle bracket, an optional slash, one or more lowercase letters, and a closing bracket. This finds both start and end tags, but only simple tags without attributes. HTML in general should be processed with an HTML parser, not with regular expressions.
Console.WriteLine($"Found {matches.Count} tags");
The Count property of the collection forces the search of the
whole input; the collection is otherwise filled lazily as it is iterated.
$ dotnet run Found 4 tags <p> at 0 <code> at 7 </code> at 18 </p> at 75
C# regex Count
The Count method, available since .NET 7, returns the number of
matches without creating Match objects. There are static and
instance versions.
using System.Text.RegularExpressions;
string content = """
Foxes are omnivorous mammals belonging to several genera
of the family Canidae. Foxes have a flattened skull, upright triangular ears,
a pointed, slightly upturned snout, and a long bushy tail. Foxes live on every
continent except Antarctica. By far the most common and widespread species of
fox is the red fox.
""";
int n1 = Regex.Count(content, "fox(es)?", RegexOptions.IgnoreCase);
Console.WriteLine($"Static Count: {n1}");
var rx = new Regex("fox(es)?");
int n2 = rx.Count(content);
Console.WriteLine($"Instance Count, case-sensitive: {n2}");
We count the occurrences of the fox word with both versions.
int n1 = Regex.Count(content, "fox(es)?", RegexOptions.IgnoreCase);
The static method takes the input, the pattern, and options.
var rx = new Regex("fox(es)?");
int n2 = rx.Count(content);
The instance method uses the pattern of the Regex object. This
pattern is case-sensitive, so the three capitalized "Foxes" are not
counted.
$ dotnet run Static Count: 5 Instance Count, case-sensitive: 2
C# regex word boundaries
The \b anchor matches at a word boundary: a position between a
word character and a non-word character, or at the start or end of the
input. It does not consume any characters. With boundaries on both sides, a
pattern matches only whole words.
using System.Text.RegularExpressions;
string text = "This island is beautiful";
foreach (Match match in Regex.Matches(text, "is"))
{
Console.WriteLine($"is: {match.Value} at {match.Index}");
}
foreach (Match match in Regex.Matches(text, @"\bis\b"))
{
Console.WriteLine($@"\bis\b: {match.Value} at {match.Index}");
}
We look for the word "is" with and without word boundaries.
foreach (Match match in Regex.Matches(text, "is"))
Without boundaries, the pattern also matches inside "This" and "island".
foreach (Match match in Regex.Matches(text, @"\bis\b"))
With boundaries, only the standalone word matches.
$ dotnet run is: is at 2 is: is at 5 is: is at 12 \bis\b: is at 12
C# regex word characters
The \w+ pattern matches a sequence of word characters, which is
a simple way to extract words. In .NET, \w is Unicode-aware and
matches letters of all alphabets. The RegexOptions.ECMAScript
option restricts it to [a-zA-Z_0-9].
using System.Text.RegularExpressions;
string content = "Foxes live on every continent except Antarctica.";
MatchCollection matches = Regex.Matches(content, @"\w+");
Console.WriteLine($"{matches.Count} words");
foreach (Match match in matches)
{
Console.Write($"[{match.Value}] ");
}
Console.WriteLine();
string text = "naïve café žltučký kůň";
Console.WriteLine(string.Join(" | ", Regex.Matches(text, @"\w+").Select(m => m.Value)));
Console.WriteLine(string.Join(" | ", Regex.Matches(text, @"\w+", RegexOptions.ECMAScript).Select(m => m.Value)));
We extract words from an English and a Slovak/Czech text.
MatchCollection matches = Regex.Matches(content, @"\w+");
Console.WriteLine($"{matches.Count} words");
The sentence has seven words; the final dot is not a word character.
Console.WriteLine(string.Join(" | ", Regex.Matches(text, @"\w+", RegexOptions.ECMAScript).Select(m => m.Value)));
With the ECMAScript behaviour, accented letters are not word characters and
the words fall apart. MatchCollection implements
IEnumerable<Match>, so LINQ methods such as
Select can be used on it directly.
$ dotnet run 7 words [Foxes] [live] [on] [every] [continent] [except] [Antarctica] naïve | café | žltučký | kůň na | ve | caf | ltu | k | k
C# regex Unicode categories
The \p{name} construct matches a character from a Unicode
category or block. For example, \p{Lu} matches uppercase
letters and \p{Sc} currency symbols.
using System.Text.RegularExpressions;
Console.OutputEncoding = System.Text.Encoding.UTF8;
string content = "Currency symbols: \u0E3F Thai baht, \u20B9 Indian rupee, "
+ "\u20BE Georgian lari, $ Dollar, \u20AC Euro, \u00A5 Yen, \u00A3 Pound";
foreach (Match match in Regex.Matches(content, @"\p{Sc}"))
{
Console.WriteLine($"{match.Value} U+{(int)match.Value[0]:X4} at {match.Index}");
}
We find the currency symbols in a text.
string content = "Currency symbols: \u0E3F Thai baht, \u20B9 Indian rupee, "
+ "\u20BE Georgian lari, $ Dollar, \u20AC Euro, \u00A5 Yen, \u00A3 Pound";
The symbols are written as \u escape sequences, which keeps the
source file ASCII-only.
foreach (Match match in Regex.Matches(content, @"\p{Sc}"))
The pattern matches any character of the currency symbol category. We print each symbol, its code point, and its position.
$ dotnet run ฿ U+0E3F at 18 ₹ U+20B9 at 31 ₾ U+20BE at 47 $ U+0024 at 64 € U+20AC at 74 ¥ U+00A5 at 82 £ U+00A3 at 89
C# regex anchors
Anchors match positions rather than characters. The ^ anchor
matches at the start of the input and $ at its end.
using System.Text.RegularExpressions;
string[] sentences =
[
"I am looking for Jane.",
"Jane was walking along the river.",
"Kate and Jane are close friends."
];
foreach (string sentence in sentences)
{
bool start = Regex.IsMatch(sentence, "^Jane");
bool end = Regex.IsMatch(sentence, @"Jane\.$");
Console.WriteLine($"{sentence,-35} start: {start,-5} end: {end}");
}
We check whether a sentence starts or ends with the name Jane.
bool start = Regex.IsMatch(sentence, "^Jane"); bool end = Regex.IsMatch(sentence, @"Jane\.$");
The dot is escaped with a backslash to match a literal dot; unescaped, it would match any character.
$ dotnet run I am looking for Jane. start: False end: True Jane was walking along the river. start: True end: False Kate and Jane are close friends. start: False end: False
C# regex alternations
The alternation operator | creates a pattern with several
choices.
using System.Text.RegularExpressions;
string[] users = ["Jane", "Thomas", "Robert", "Lucy", "Beky",
"John", "Peter", "Andy", "Janet"];
var rx = new Regex("^(Jane|Beky|Robert)$");
foreach (string user in users)
{
if (rx.IsMatch(user))
{
Console.WriteLine($"{user} does match");
}
}
We look for three names in a list of users.
var rx = new Regex("^(Jane|Beky|Robert)$");
The alternation has the lowest precedence, so ^Jane|Beky$ would
mean "Jane at the start, or Beky at the end". We group the alternatives with
parentheses and anchor the group, so the name must match exactly. Without
the anchors, "Janet" would match too.
$ dotnet run Jane does match Robert does match Beky does match
C# regex capturing groups
Parentheses create capturing groups. A group remembers the part of the
match it matched; the groups are numbered from one by their opening
parenthesis and are accessed through the Groups property. Group
0 is the whole match.
using System.Text.RegularExpressions;
string[] sites = ["zetcode.com", "freebsd.org", "kernel.org", "localhost"];
var rx = new Regex(@"(\w+)\.(\w+)");
foreach (string site in sites)
{
Match match = rx.Match(site);
if (match.Success)
{
Console.WriteLine($"{match.Groups[0]}: {match.Groups[1]} + {match.Groups[2]}");
}
else
{
Console.WriteLine($"{site}: no match");
}
}
We divide domain names into two parts.
var rx = new Regex(@"(\w+)\.(\w+)");
The two groups capture the words before and after the dot.
Console.WriteLine($"{match.Groups[0]}: {match.Groups[1]} + {match.Groups[2]}");
A Group object converts to its matched text in string
interpolation.
$ dotnet run zetcode.com: zetcode + com freebsd.org: freebsd + org kernel.org: kernel + org localhost: no match
C# regex calculator
Groups are useful for parsing structured input. In the following example, we parse and compute simple arithmetic expressions.
using System.Text.RegularExpressions;
string[] expressions = ["16 + 11", "12 * 5", "27 / 3", "2 - 8", "7 % 2"];
var rx = new Regex(@"^(\d+)\s*([-+*/])\s*(\d+)$");
foreach (string expression in expressions)
{
Match match = rx.Match(expression);
if (!match.Success)
{
Console.WriteLine($"{expression}: invalid expression");
continue;
}
int val1 = int.Parse(match.Groups[1].Value);
string oper = match.Groups[2].Value;
int val2 = int.Parse(match.Groups[3].Value);
int result = oper switch
{
"+" => val1 + val2,
"-" => val1 - val2,
"*" => val1 * val2,
"/" => val1 / val2,
_ => throw new InvalidOperationException(oper)
};
Console.WriteLine($"{expression} = {result}");
}
The pattern has three groups: two for the operands and one for the operator.
var rx = new Regex(@"^(\d+)\s*([-+*/])\s*(\d+)$");
We create the Regex once, outside the loop. Inside a character
class, the hyphen is a literal when it comes first, so
[-+*/] matches the four operators. The anchors reject
expressions with any extra text.
int val1 = int.Parse(match.Groups[1].Value); string oper = match.Groups[2].Value; int val2 = int.Parse(match.Groups[3].Value);
We read the groups and convert the operands to integers. The switch expression then computes the result.
$ dotnet run 16 + 11 = 27 12 * 5 = 60 27 / 3 = 9 2 - 8 = -6 7 % 2: invalid expression
C# regex named groups
The (?<name>...) syntax creates a named group, which can
be accessed by its name instead of its number. Named groups make longer
patterns easier to read and maintain.
using System.Text.RegularExpressions;
string log = """
2026-11-02 ERROR disk full
2026-11-03 INFO backup done
2026-11-15 WARN high load
""";
var rx = new Regex(@"(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2}) (?<level>\w+)");
foreach (Match m in rx.Matches(log))
{
string date = $"{m.Groups["day"]}.{m.Groups["month"]}.{m.Groups["year"]}";
Console.WriteLine($"{date} {m.Groups["level"].Value}");
}
Match first = rx.Match(log);
Console.WriteLine(string.Join(", ", first.Groups.Keys));
We parse the dates and levels of log lines.
var rx = new Regex(@"(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2}) (?<level>\w+)");
Each part of the date and the log level has its own named group.
string date = $"{m.Groups["day"]}.{m.Groups["month"]}.{m.Groups["year"]}";
The groups are accessed with string indexes. We reformat the date.
Console.WriteLine(string.Join(", ", first.Groups.Keys));
The Keys property of the group collection lists the group
names. Group 0, the whole match, is always present.
$ dotnet run 02.11.2026 ERROR 03.11.2026 INFO 15.11.2026 WARN 0, year, month, day, level
C# regex captures
When a quantifier is applied to a group, the group can match several times
within one match. The Value of the group holds only the last
matched substring; all of them are available in the
Captures property.
using System.Text.RegularExpressions;
string text = "Today is a beautiful day. The sun is shining.";
string pattern = @"\b(\w+\s*)+\.";
foreach (Match match in Regex.Matches(text, pattern))
{
Console.WriteLine($"Matched sentence: {match.Value}");
Group group = match.Groups[1];
Console.WriteLine($" Group 1 value: '{group.Value}'");
for (int i = 0; i < group.Captures.Count; i++)
{
Console.WriteLine($" Capture {i}: '{group.Captures[i].Value}'");
}
}
We match sentences and list their words.
string pattern = @"\b(\w+\s*)+\.";
The (\w+\s*) group matches a word with the white space that
follows it. The + quantifier repeats the group for every word
of the sentence, up to the final dot.
for (int i = 0; i < group.Captures.Count; i++)
{
Console.WriteLine($" Capture {i}: '{group.Captures[i].Value}'");
}
We print all captures of the group. The quotes reveal the trailing spaces that are part of the captures.
$ dotnet run
Matched sentence: Today is a beautiful day.
Group 1 value: 'day'
Capture 0: 'Today '
Capture 1: 'is '
Capture 2: 'a '
Capture 3: 'beautiful '
Capture 4: 'day'
Matched sentence: The sun is shining.
Group 1 value: 'shining'
Capture 0: 'The '
Capture 1: 'sun '
Capture 2: 'is '
Capture 3: 'shining'
C# regex multiline option
The RegexOptions.Multiline option changes the meaning of the
^ and $ anchors: they match at the start and end
of every line, not only of the whole input.
using System.Text.RegularExpressions;
string text = "apple\nbanana\napple pie\ncherry\napple tart";
foreach (Match m in Regex.Matches(text, "^apple"))
{
Console.WriteLine($"Without Multiline: {m.Value} at {m.Index}");
}
foreach (Match m in Regex.Matches(text, "^apple", RegexOptions.Multiline))
{
Console.WriteLine($"With Multiline: {m.Value} at {m.Index}");
}
foreach (Match m in Regex.Matches(text, @"\w+$", RegexOptions.Multiline))
{
Console.WriteLine($"Last word of a line: {m.Value}");
}
We search for the word apple at the start of the lines of a text.
foreach (Match m in Regex.Matches(text, "^apple"))
Without the option, ^apple matches only at the start of the
input.
foreach (Match m in Regex.Matches(text, "^apple", RegexOptions.Multiline))
With the option, it matches at the start of the three lines that begin with "apple".
foreach (Match m in Regex.Matches(text, @"\w+$", RegexOptions.Multiline))
In multiline mode, $ matches before each newline, so we get the
last word of every line. Note that $ matches before
\n only; with Windows line endings, use \r?$.
$ dotnet run Without Multiline: apple at 0 With Multiline: apple at 0 With Multiline: apple at 13 With Multiline: apple at 30 Last word of a line: apple Last word of a line: banana Last word of a line: pie Last word of a line: cherry Last word of a line: tart
C# regex Replace
The Replace method returns a new string in which all matches are
replaced. The replacement string can refer to groups: $1
inserts the text of group 1 and ${name} the text of a named
group.
using System.Text.RegularExpressions;
string html = """
<html>
<body>
<h1>Today's news</h1>
<p>Prices rose by <b>3%</b> in <em>October</em>.</p>
</body>
</html>
""";
string text = Regex.Replace(html, "<[^>]*>", string.Empty);
text = Regex.Replace(text, @"\n{2,}", "\n").Trim();
Console.WriteLine(text);
string dates = "Released on 2026-11-10, patched on 2026-11-14.";
Console.WriteLine(Regex.Replace(dates, @"(\d{4})-(\d{2})-(\d{2})", "$3.$2.$1"));
Console.WriteLine(Regex.Replace(dates,
@"(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})", "${m}/${d}/${y}"));
We strip the tags from an HTML document and reformat dates.
string text = Regex.Replace(html, "<[^>]*>", string.Empty);
text = Regex.Replace(text, @"\n{2,}", "\n").Trim();
The <[^>]*> pattern matches anything from an opening to
a closing angle bracket. We remove the tags and then collapse the empty lines
they leave behind.
Console.WriteLine(Regex.Replace(dates, @"(\d{4})-(\d{2})-(\d{2})", "$3.$2.$1"));
The ISO dates are converted to the day.month.year format by reordering the numbered groups.
Console.WriteLine(Regex.Replace(dates,
@"(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})", "${m}/${d}/${y}"));
The same with named groups, this time to the US format.
$ dotnet run Today's news Prices rose by 3% in October. Released on 10.11.2026, patched on 14.11.2026. Released on 11/10/2026, patched on 11/14/2026.
C# regex Replace with MatchEvaluator
When the replacement must be computed, Replace accepts a
MatchEvaluator delegate. It is called for each match and returns
the replacement text.
using System.Text.RegularExpressions;
string text = "The order contains 3 apples, 12 oranges and 7 pears.";
string doubled = Regex.Replace(text, @"\d+", m => (int.Parse(m.Value) * 2).ToString());
Console.WriteLine(doubled);
string title = Regex.Replace("an old falcon in the sky", @"\b\w",
m => m.Value.ToUpperInvariant());
Console.WriteLine(title);
string masked = Regex.Replace("Card: 4111 1111 1111 1234", @"\d{4}(?= )", "****");
Console.WriteLine(masked);
We double the numbers in a text and capitalize words.
string doubled = Regex.Replace(text, @"\d+", m => (int.Parse(m.Value) * 2).ToString());
The lambda receives each number as a Match, parses it, and
returns the doubled value.
string title = Regex.Replace("an old falcon in the sky", @"\b\w",
m => m.Value.ToUpperInvariant());
The \b\w pattern matches the first letter of each word, which
we convert to uppercase.
string masked = Regex.Replace("Card: 4111 1111 1111 1234", @"\d{4}(?= )", "****");
This replacement uses a plain string. The (?= ) lookahead,
covered later, limits the match to digit groups followed by a space, so the
last group stays visible.
$ dotnet run The order contains 6 apples, 24 oranges and 14 pears. An Old Falcon In The Sky Card: **** **** **** 1234
C# regex Split
The Split method splits a string at the matches of the pattern.
Unlike String.Split, the separator can be any pattern.
22, 1, 3, 4, 5, 17, 18, 2, 13, 4, 1, 8, 4, 3, 21, 4, 5, 1, 48, 9, 42
We read numbers from this CSV file.
using System.Text.RegularExpressions;
string content = File.ReadAllText("data.csv");
string[] data = Regex.Split(content.Trim(), @",\s*");
Console.WriteLine($"[{string.Join(", ", data)}]");
int sum = data.Sum(int.Parse);
Console.WriteLine($"Sum: {sum}");
string[] parts = Regex.Split("one1two22three333four", @"\d+");
Console.WriteLine(string.Join(" ", parts));
string[] kept = Regex.Split("10+20-5", @"([-+])");
Console.WriteLine(string.Join(" ", kept));
The example splits the file content into numbers and computes their sum.
string[] data = Regex.Split(content.Trim(), @",\s*");
The separator is a comma followed by zero or more white space characters, including the newlines. We trim the content first; otherwise the final newline would produce a trailing element.
int sum = data.Sum(int.Parse);
The int.Parse method group serves as the selector of
Sum.
string[] kept = Regex.Split("10+20-5", @"([-+])");
If the pattern contains a capturing group, the captured separators are included in the result.
$ dotnet run [22, 1, 3, 4, 5, 17, 18, 2, 13, 4, 1, 8, 4, 3, 21, 4, 5, 1, 48, 9, 42] Sum: 235 one two three four 10 + 20 - 5
C# case-insensitive regular expression
The RegexOptions.IgnoreCase option enables case-insensitive
matching. The same can be done inside the pattern with the
(?i) inline option.
using System.Text.RegularExpressions;
string[] words = ["dog", "Dog", "DOG", "Doggy"];
var rx = new Regex(@"\bdog\b", RegexOptions.IgnoreCase);
foreach (string word in words)
{
Console.WriteLine($"{word}: {rx.IsMatch(word)}");
}
Console.WriteLine($"Inline option: {Regex.IsMatch("DOG", "(?i)dog")}");
We match the word dog regardless of case.
var rx = new Regex(@"\bdog\b", RegexOptions.IgnoreCase);
The option is passed to the constructor. "Doggy" does not match because of the trailing word boundary.
Console.WriteLine($"Inline option: {Regex.IsMatch("DOG", "(?i)dog")}");
The inline option is handy where options cannot be passed, for example in patterns stored in configuration files.
$ dotnet run dog: True Dog: True DOG: True Doggy: False Inline option: True
C# regex subpatterns
A group with a quantifier makes a whole subpattern optional or repeated.
using System.Text.RegularExpressions;
string[] words = ["book", "bookshelf", "bookworm", "bookcase", "bookish",
"bookkeeper", "booklet", "bookmark"];
var rx = new Regex("^book(worm|mark|keeper)?$");
foreach (string word in words)
{
if (rx.IsMatch(word))
{
Console.WriteLine($"{word} does match");
}
else
{
Console.WriteLine($"{word} does not match");
}
}
We match the word book with an optional suffix.
var rx = new Regex("^book(worm|mark|keeper)?$");
The pattern matches book, bookworm, bookmark, and bookkeeper. The
? applies to the whole group.
$ dotnet run book does match bookshelf does not match bookworm does match bookcase does not match bookish does not match bookkeeper does match booklet does not match bookmark does match
C# regex word frequency
In the next example, we count the frequency of words in a book. We download the text of Pride and Prejudice from Project Gutenberg.
using System.Text.RegularExpressions;
using var client = new HttpClient();
string text = await client.GetStringAsync("https://www.gutenberg.org/cache/epub/1342/pg1342.txt");
var words = Regex.Matches(text, @"[a-zA-Z]+(?:'[a-zA-Z]+)?")
.Select(m => m.Value.ToLowerInvariant());
var top = words
.CountBy(w => w)
.OrderByDescending(e => e.Value)
.Take(10);
foreach (var (word, count) in top)
{
Console.WriteLine($"{word}: {count}");
}
The program extracts words with a regular expression and counts them with LINQ.
var words = Regex.Matches(text, @"[a-zA-Z]+(?:'[a-zA-Z]+)?")
.Select(m => m.Value.ToLowerInvariant());
A word is a sequence of letters, optionally followed by an apostrophe and
more letters, so contractions like "don't" stay whole. The
(?:...) syntax is a non-capturing group: it groups without
capturing. We convert the words to lowercase so that "The" and "the" are
counted together.
var top = words
.CountBy(w => w)
.OrderByDescending(e => e.Value)
.Take(10);
CountBy, added in .NET 9, returns key/value pairs with the
number of occurrences of each word. We sort them and take the ten most
frequent words.
$ dotnet run the: 4853 to: 4407 of: 3966 and: 3839 her: 2284 i: 2122 a: 2096 in: 2054 was: 1878 she: 1751
C# regex email example
In the following example, we create a pattern for checking email addresses.
using System.Text.RegularExpressions;
string[] emails = ["luke@gmail.com", "andy@yahoocom", "34234sdfa#2345",
"f344@gmail.com", "jane.doe@mail.co.uk"];
var rx = new Regex(@"^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,18}$");
foreach (string email in emails)
{
if (rx.IsMatch(email))
{
Console.WriteLine($"{email} does match");
}
else
{
Console.WriteLine($"{email} does not match");
}
}
The pattern is a simple approximation. Fully validating email addresses with a regular expression is impractical; real applications check the basic shape and confirm the address by sending a message to it.
var rx = new Regex(@"^[a-zA-Z0-9._-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]{2,18}$");
The pattern has five parts. [a-zA-Z0-9._-]+ is the local part:
one or more letters, digits, dots, underscores, or hyphens. Then comes the
literal @ character, followed by the domain name
[a-zA-Z0-9-]+. The escaped dot matches a literal dot. The final
part [a-zA-Z.]{2,18} is the top-level domain; it may contain a
dot for two-part domains like co.uk. The anchors make the pattern match the
whole input.
$ dotnet run luke@gmail.com does match andy@yahoocom does not match 34234sdfa#2345 does not match f344@gmail.com does match jane.doe@mail.co.uk does match
C# regex lookahead and lookbehind
Lookahead and lookbehind assertions match a position based on what follows or precedes it. Like anchors, they are zero-width: they do not consume characters and are not part of the match.
(?=...)positive lookahead: followed by the pattern,(?!...)negative lookahead: not followed by the pattern,(?<=...)positive lookbehind: preceded by the pattern,(?<!...)negative lookbehind: not preceded by the pattern.
using System.Text.RegularExpressions;
string text = "catfish catnap dogfish dogcat";
Show("cat(?=fish)", text);
Show("cat(?!fish)", text);
Show("(?<=dog)fish", text);
Show("(?<!dog)cat", text);
static void Show(string pattern, string text)
{
var found = Regex.Matches(text, pattern).Select(m => $"{m.Value} at {m.Index}");
Console.WriteLine($"{pattern,-14} {string.Join(", ", found)}");
}
We apply the four assertions to the same text.
Show("cat(?=fish)", text);
Show("cat(?!fish)", text);
The first pattern matches cat only in catfish; the second matches it in catnap and dogcat.
Show("(?<=dog)fish", text);
Show("(?<!dog)cat", text);
The lookbehinds match the fish of dogfish, and every cat that is not part of dogcat.
$ dotnet run cat(?=fish) cat at 0 cat(?!fish) cat at 8, cat at 26 (?<=dog)fish fish at 18 (?<!dog)cat cat at 0, cat at 8
C# GeneratedRegex
The GeneratedRegex attribute, available since .NET 7, makes a
source generator emit C# code for the pattern at compile time. The pattern
is validated by the compiler, there is no parsing at startup, and the
generated code is as fast as RegexOptions.Compiled without its
startup cost. It is the recommended way to use patterns known at compile
time.
using System.Text.RegularExpressions;
string[] inputs = ["2026-11-15", "15.11.2026", "2026-1-5"];
foreach (string input in inputs)
{
Console.WriteLine($"{input}: {Patterns.IsoDate.IsMatch(input)}");
}
string text = "Call 555-1234 or 555-9876 today.";
foreach (ValueMatch m in Patterns.Phone().EnumerateMatches(text))
{
Console.WriteLine(text.AsSpan(m.Index, m.Length).ToString());
}
static partial class Patterns
{
[GeneratedRegex(@"^\d{4}-\d{2}-\d{2}$")]
public static partial Regex IsoDate { get; }
[GeneratedRegex(@"\d{3}-\d{4}")]
public static partial Regex Phone();
}
The attribute is applied to a partial method or, since .NET 9, a partial property of a partial class.
static partial class Patterns
{
[GeneratedRegex(@"^\d{4}-\d{2}-\d{2}$")]
public static partial Regex IsoDate { get; }
[GeneratedRegex(@"\d{3}-\d{4}")]
public static partial Regex Phone();
}
The generator provides the implementations, which return cached
Regex instances. In a program with top-level statements, type
declarations come after the statements.
foreach (ValueMatch m in Patterns.Phone().EnumerateMatches(text))
{
Console.WriteLine(text.AsSpan(m.Index, m.Length).ToString());
}
The EnumerateMatches method returns the matches as
ValueMatch structures with only an index and a length. It works
on spans and does not allocate Match objects, which matters in
hot paths.
$ dotnet run 2026-11-15: True 15.11.2026: False 2026-1-5: False 555-1234 555-9876
C# regex timeouts and NonBacktracking
The default regex engine uses backtracking. Some patterns, such as nested
quantifiers, need exponential time on certain inputs; this is called
catastrophic backtracking. When patterns or inputs come from users, it can be
abused for denial-of-service attacks. A match timeout limits the time a
match may take, and the RegexOptions.NonBacktracking engine,
added in .NET 7, guarantees time linear in the length of the input.
using System.Diagnostics;
using System.Text.RegularExpressions;
string input = new string('a', 30) + "!";
string pattern = "^(a+)+$";
var sw = Stopwatch.StartNew();
try
{
var rx = new Regex(pattern, RegexOptions.None, TimeSpan.FromMilliseconds(200));
Console.WriteLine(rx.IsMatch(input));
}
catch (RegexMatchTimeoutException e)
{
Console.WriteLine($"Timed out after {e.MatchTimeout.TotalMilliseconds} ms");
}
sw.Restart();
var nb = new Regex(pattern, RegexOptions.NonBacktracking);
bool result = nb.IsMatch(input);
Console.WriteLine($"NonBacktracking: {result}, under 100 ms: {sw.ElapsedMilliseconds < 100}");
We match the ^(a+)+$ pattern against thirty a's followed by an
exclamation mark.
var rx = new Regex(pattern, RegexOptions.None, TimeSpan.FromMilliseconds(200));
The match fails, but the backtracking engine tries every way of dividing the
a's between the inner and outer quantifier before it can tell, which would
take far longer than the timeout. The engine throws a
RegexMatchTimeoutException after 200 ms.
var nb = new Regex(pattern, RegexOptions.NonBacktracking);
The non-backtracking engine finds the same result immediately. It does not support some constructs, such as lookarounds and backreferences.
$ dotnet run Timed out after 200 ms NonBacktracking: False, under 100 ms: True
Source
In this article we have worked with regular expressions in C#. See also the string, split string, and LINQ tutorials.
Author
List all C# tutorials.