Regex
GroupsIn C# Regex.Match
returns a Match
object. The Groups property on a Match
gets the captured groups within the regular expression.
This property is useful for extracting a part of a string
from a match. It can be used with multiple captured parts. Groups can be accessed with an int
or string
.
Regular expressions are more powerful than most string
methods. Regex
lets you specify substrings with a certain range of characters, such as "A-Za-z0-9."
string
literal syntax. It escapes characters differently than other string
literals.Match
on the Regex
we created. This returns a Match
object. We extract the capture from this object.using System; using System.Text.RegularExpressions; class Program { static void Main() { // Part 1: the input string we are using. string input = "a45"; // Part 2: the regular expression we use to match. Regex regex = new Regex(@"a(\d)(\d)"); // Part 3: match the input and write results. Match match = regex.Match(input); if (match.Success) { string value1 = match.Groups[1].Value; string value2 = match.Groups[2].Value; Console.WriteLine("GROUP 1 and 2: {0}, {1}", value1, value2); } } }GROUP 1 and 2: 4, 5
Here we use a named group in a regular expression. We then access the value of the string
that matches that group with the Groups property. We use a string
index key.
string
has the number 12345 in the middle of two strings. We match this in a named group called "middle."using System; using System.Text.RegularExpressions; class Program { static void Main() { // ... Input string. string input = "Left12345Right"; // ... Use named group in regular expression. Regex expression = new Regex(@"Left(?<middle>\d+)Right"); // ... See if we matched. Match match = expression.Match(input); if (match.Success) { // ... Get group by name. string result = match.Groups["middle"].Value; Console.WriteLine("Middle: {0}", result); } } }Middle: 12345
Regular expressions are not needed for simple parsing tasks. Consider a specialized method that can access strings between, before and after other strings.
You can find a string
between two delimiters of multiple characters. With Groups, we can access "captured" values with an int
or string
.