Home > Article > Backend Development > How do Regular Expression Groups Work in C#?
Regular Expression Groups in C#
In the following code block, the provided regex extracts the contents within square brackets:
var pattern = @"\[(.*?)\]"; var matches = Regex.Matches(user, pattern);
With the input user == "Josh Smith [jsmith]":
matches.Count == 1 matches[0].Value == "[jsmith]"
However, matches[0].Groups.Count == 2, with:
matches[0].Groups[0].Value == "[jsmith]" matches[0].Groups[1].Value == "jsmith"
Understanding the Group Collection
In this case:
Therefore, match.Groups[1].Value retrieves the contents within the brackets, "jsmith".
Count of Groups in a Match
The following rules govern the number of groups in a match:
In the provided example, since pattern contains one capturing group, match.Groups.Count will always be 2. However, more complex regular expressions with multiple capturing groups will result in a greater number of groups.
Additional Examples
Consider the following pattern and match:
var pattern = @"\[(.*?)\](.*)"; var match = Regex.Match("ignored [john] John Johnson", pattern);
In a more complex pattern:
var pattern = @"(\[.*?\])+"; var match = Regex.Match("[john][johnny]", pattern);
Understanding these concepts is crucial for harnessing the power of regular expression groups in C#.
The above is the detailed content of How do Regular Expression Groups Work in C#?. For more information, please follow other related articles on the PHP Chinese website!