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
| Flag | Description |
|---|---|
RegexFlags.None | Default matching |
RegexFlags.IgnoreCase | Case-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")}"); // trueConsole.WriteLine($"{re.IsMatch("No date here")}"); // falseStatic 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
| Property | Type | Description |
|---|---|---|
m.Success | bool | Whether a match was found |
m.Index | int | Start position in input |
m.Length | int | Length of match |
m.Value | string | Matched text |
m.Next | Match | Next 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 onlySplitting
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
| Member | Description |
|---|---|
r.Pattern | The regex pattern string |
r.Flags | The flags used |
r.GroupCount | Number of capture groups |
r.IsValid | Whether 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 |