C# Reference ยท Strings and Text
Regex.Match() and Regex.Matches()
Reference for Regex.Match, Matches and EnumerateMatches in C#: read Value, Index, Groups and Captures, iterate matches and avoid allocations.
Regex.Match finds the first occurrence of a pattern and returns a Match object. Regex.Matches finds all non-overlapping occurrences and returns a MatchCollection. Both give you more than a yes or no: the matched text, its position, and every captured group.
Always check Match.Success before reading from a match. A failed match is not null; it is a Match whose Success is false and whose Value is empty. Since .NET 7, EnumerateMatches offers a version that allocates nothing, for when you only need positions.
Match m = Regex.Match("id=42", @"id=(\d+)"); if (m.Success) { Console.WriteLine(m.Groups[1].Value); // 42 }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public Match Match(string input) public Match Match(string input, int startat) public Match Match(string input, int beginning, int length) public static Match Match(string input, string pattern) public MatchCollection Matches(string input) public static MatchCollection Matches(string input, string pattern) public ValueMatchEnumerator EnumerateMatches(ReadOnlySpan<char> input) public Match NextMatch()
| Name | Description |
|---|---|
input |
The text to search. |
startat |
Index where the search starts. Anchors and lookbehinds still see the whole string. |
beginning, length |
A substring to search; here ^ and $ apply to that substring only. |
pattern |
The regular expression (static overloads). |
Returns: a Match (Success, Value, Index, Length, Groups, NextMatch()), a MatchCollection, or an enumerator of ValueMatch structs with Index and Length only.
Errors / undefined behavior: ArgumentNullException for null input. RegexParseException for a bad pattern. RegexMatchTimeoutException if a timeout is set and expires. startat outside 0..input.Length throws ArgumentOutOfRangeException.
Usage notes
- Check
Success. ReadingGroups[1].Valueafter a failed match returns an empty string, which hides bugs. - Group 0 is the whole match. Numbered groups start at 1 and count left parentheses. Named groups are numbered after the unnamed ones, so mixing styles gives surprising numbers; use names consistently.
- Optional groups. A group that did not participate has
Success == falseand an emptyValue. TestGroups["x"].Successto tell "absent" from "empty". Captureshold every repetition of a group inside a quantifier;Groups[n].Valueholds only the last.MatchCollectionis lazy. Matches are found as you enumerate, soCountforces the whole scan, and enumerating twice does not search twice. With a short timeout a failure can appear in the middle of the loop.- Empty matches advance. Patterns that can match nothing (
x*) produce an empty match at every position, which is almost never what you want. - Use
EnumerateMatchesin hot paths. It works on spans, allocates noMatchobjects, and is ideal when you only need offsets. It cannot give you groups. - Single match with LINQ.
MatchesimplementsIEnumerable<Match>, soSelect,WhereandCountwork directly.
Related
Regex, Regex syntax,Regex.Replace(),RegexOptions- Lessons: Regular Expressions