Skip to content

Regex

Overview

The Regex type provides regular expression support.

Creating a Regex

Regex re = Regex("[a-z]+");
Regex re2 = Regex("[A-Z]+", RegexFlags.IgnoreCase);

Flags

FlagDescription
RegexFlags.NoneDefault matching
RegexFlags.IgnoreCaseCase-insensitive matching
RegexFlags.Multiline^ and $ match line boundaries

Testing for a Match

Regex re = Regex("\\d{4}-\\d{2}-\\d{2}");
Console.WriteLine($"{re.IsMatch("Today is 2025-06-15")}"); // true
Console.WriteLine($"{re.IsMatch("No date here")}"); // false

Static Shorthand

bool found = Regex.IsMatch("hello 123", "\\d+");

Finding Matches

First Match

Regex re = Regex("\\w+@\\w+\\.\\w+");
Match m = re.Match("Contact: alice@example.com");
if (m.Success)
{
Console.WriteLine(m.Value);
Console.WriteLine($"{m.Index}");
Console.WriteLine($"{m.Length}");
}

Match From Offset

Match m2 = re.MatchFrom("alice@a.com bob@b.com", 12);

All Matches

Regex re = Regex("\\d+");
Match[*] matches = re.MatchAll("abc 123 def 456");
for (int i = 0; i < matches.Length; i++)
{
Console.WriteLine(matches[i].Value);
}

Match Properties

PropertyTypeDescription
m.SuccessboolWhether a match was found
m.IndexintStart position in input
m.LengthintLength of match
m.ValuestringMatched text
m.NextMatchNext match in sequence

Replacement

Regex re = Regex("world");
string result = re.Replace("hello world", "Cera"); // "hello Cera"
string first = re.ReplaceFirst("aaa bbb aaa", "ccc"); // replaces first only

Splitting

Regex re = Regex("\\s+");
string[*] parts = re.Split("one two three"); // ["one", "two", "three"]

Capture Groups

Regex re = Regex("(\\d{4})-(\\d{2})-(\\d{2})");
string[*] groups = re.Capture("2025-06-15");
// groups[0] = "2025-06-15" (full match)
// groups[1] = "2025", groups[2] = "06", groups[3] = "15"

Capture From Offset

string[*] groups = re.CaptureFrom("date: 2025-06-15", 6);

Named Captures

Use named groups and retrieve them as name/value pairs:

Regex re = Regex("(?<year>\\d{4})-(?<month>\\d{2})");
string[*] named = re.CaptureNamed("2026-02");
// named = ["year", "2026", "month", "02"]

CaptureNamed returns a flat array of alternating name and value strings.

CompiledRegex

For repeated matching, pre-compile a regex into a DFA for faster execution:

CompiledRegex cr = Regex.Compile("\\d+", RegexFlags.None);
Console.WriteLine($"{cr.IsMatch("hello123")}"); // true
Match m = cr.Match("abc 42 def");
Console.WriteLine(m.Value); // "42"

CompiledRegex has the same methods and properties as Regex (IsMatch, Match, MatchFrom, MatchAll, Replace, Split, Capture, etc.).

Other Properties and Methods

MemberDescription
r.PatternThe regex pattern string
r.FlagsThe flags used
r.GroupCountNumber of capture groups
r.IsValidWhether the pattern compiled
Regex.Compile(pat, flags)Pre-compile a pattern into CompiledRegex
Regex.Escape(s)Escape special characters
Regex.IsMatch(pattern, text)One-shot static match test