Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Sometimes it’s useful to separate a regular expression into a series of subexpressions, or groups. For instance, consider the following regular expression that represents a U.S. phone number such as 206-465-1918:
\d{3}-\d{3}-\d{4}
Suppose we wish to separate this into two groups: area code and local number. We can achieve this by using parentheses to capture each group:
(\d{3})-(\d{3}-\d{4})
We then retrieve the groups programmatically as follows:
Match m = Regex.Match ("206-465-1918", @"(\d{3})-(\d{3}-\d{4})");
Console.WriteLine (m.Groups[1]); // 206
Console.WriteLine (m.Groups[2]); // 465-1918
The zeroth group represents the entire match. In other words, it has
the same value as the match’s Value:
Console.WriteLine (m.Groups[0]); // 206-465-1918 Console.WriteLine (m); // 206-465-1918