Regex
System.Text.RegularExpressions.Regex compiles a pattern and matches it against a string. The pattern language is the same one most languages share, and the C# API adds groups by name, a match timeout, and a source generator that builds the matcher at compile time.
Groups and named groups
Parentheses capture a part of the match. A group is read by its number, counting the opening parentheses from the left, or by a name written (?<name>...):
using System.Text.RegularExpressions;
var pattern = new Regex(@"(\w+)@(\w+)\.(\w+)");
var match = pattern.Match("write to ada@example.com today");
Console.WriteLine($"success {match.Success}");
Console.WriteLine($"value {match.Value}");
Console.WriteLine($"user {match.Groups[1].Value}");
Console.WriteLine($"host {match.Groups[2].Value}");
Console.WriteLine($"top {match.Groups[3].Value}");
var named = new Regex(@"(?<user>\w+)@(?<host>[\w.]+)");
var hit = named.Match("ada@example.com");
Console.WriteLine($"user {hit.Groups["user"].Value}");
Console.WriteLine($"host {hit.Groups["host"].Value}");
dotnet run
success True
value ada@example.com
user ada
host example
top com
user ada
host example.com
Match finds the first occurrence anywhere in the string, which is why the leading words do not stop it. The named pattern reads the same text with clearer code: the second group of the named pattern is [\w.]+ and takes the whole domain, while the numbered one stopped at the first dot. Match returns a Match whose Success is false when nothing matched, so a missing match is not an exception.
Replace and Split
Regex.Replace replaces every match, and Regex.Split cuts the string at the matches. Both take the pattern and the text, and neither changes the original string, which is immutable:
using System.Text.RegularExpressions;
var replaced = Regex.Replace("one 1 two 22", @"\d+", "#");
Console.WriteLine($"replaced {replaced}");
var parts = Regex.Split("a,b; c", @"[,;] ");
Console.WriteLine($"split {string.Join("|", parts)}");
var groups = Regex.Replace("2024-03-10", @"(\d{4})-(\d{2})-(\d{2})", "$3.$2.$1");
Console.WriteLine($"reordered {groups}");
dotnet run
replaced one # two #
split a,b|c
reordered 10.03.2024
The replacement string may name a group as $1, which is how a date is reordered without parsing it. A literal dollar sign in a replacement is written $$. The split produced three parts, because the pattern matched the comma and the semicolon and the space after each, so the space before the semicolon stayed with the second part.
A timeout
A pattern with nested quantifiers can take an exponential time on a string that almost matches. A production program passes a timeout, and the failure is then an exception instead of a request that never ends:
using System.Text.RegularExpressions;
try
{
var slow = new Regex(@"^(a+)+$", RegexOptions.None, TimeSpan.FromMilliseconds(50));
slow.IsMatch(new string('a', 40) + "b");
}
catch (RegexMatchTimeoutException e)
{
Console.WriteLine($"timeout {e.GetType().Name}");
Console.WriteLine($"after {e.MatchTimeout.TotalMilliseconds}");
}
Console.WriteLine("after the catch");
dotnet run
timeout RegexMatchTimeoutException
after 50
after the catch
Forty a characters followed by a b make the pattern try every way of splitting the run before it fails, and the engine stopped after the fifty milliseconds it was given. The exception carries the timeout that was set. A static method such as Regex.IsMatch reads a default timeout from the application configuration; a pattern written once and used many times gets its own.
[GeneratedRegex]
The source generator in the SDK can turn a constant pattern into code at build time, which skips the parsing at run time. The attribute goes on a partial method of a partial class, and a top-level program already has that class:
using System.Text.RegularExpressions;
var words = Word().Matches("one two three");
Console.WriteLine($"generated {words.Count}");
int total = 0;
foreach (Match word in Number().Matches("a1 b22 c333"))
{
total += int.Parse(word.Value);
}
Console.WriteLine($"total {total}");
partial class Program
{
[GeneratedRegex(@"\b\w+\b")]
private static partial Regex Word();
[GeneratedRegex(@"\d+")]
private static partial Regex Number();
}
dotnet run
generated 3
total 356
The generator wrote the matcher, so both calls are ordinary method calls with no pattern string to parse. The rule is the one the compiler enforces: a generated method must be partial, static, and take no arguments, and its class must be partial too. The lesson on source generators explains what the generator is and why one from NuGet needs the network while this one does not.
Exercises
- Write a pattern that matches a date in ISO form and reads its three parts.
- Replace every word in a sentence with its length, using a match evaluator.
- Find a pattern with a timeout of one millisecond that fails on a short string and read the exception.
- Rewrite one of the patterns as a [GeneratedRegex] method and compare the code.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which class compiles and applies a regular expression?
Answer
Regex
Regex holds the pattern; Match is one result of it.
-
What does match.Groups[1] return?
Answer
The first capturing group
Group 0 is the whole match and the numbered groups follow the parentheses.
-
What does this program print?
using System.Text.RegularExpressions; Console.WriteLine(Regex.Matches("a1b2", @"\d").Count);Answer
2
Two digits match, 1 and 2.
-
How is a named group read from a match?
Answer
match.Groups["name"].Value
A named group is still a group of the same collection, under its name.
-
What does this program print?
using System.Text.RegularExpressions; Console.WriteLine(Regex.Replace("a1", @"\d", "#"));Answer
a#
The digit is replaced by the hash and the letter stays.
-
What does RegexOptions.IgnoreCase change?
Answer
The match ignores the case of letters
It is the same as the inline (?i) option.
-
What does a RegexMatchTimeoutException mean?
Answer
The match took longer than the timeout given to the Regex
The measured pattern stopped after the fifty milliseconds it was given.
-
What does [GeneratedRegex] require of its method?
Answer
It must be partial, static and take no arguments
The generator writes the body of that partial method at build time.
-
What does this program print?
using System.Text.RegularExpressions; Console.WriteLine(new Regex(@"\d+").IsMatch("abc"));Answer
False
There is no digit in the string, so IsMatch is false.
-
What does Regex.Split do?
Answer
Cuts the string at every match
The measured call split at the comma and the semicolon with the space after them.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev