C# Regex Groups, Named Group ExampleUse the Groups property on a Match result. Access named groups with a string.
dot net perls
Regex Groups. In C# Regex.Match returns a Match object. The Groups property on a Match gets the captured groups within the regular expression.
Groups info. 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.
An example. 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."
Part A This is the input string we are matching. Notice how it contains 3 uppercase words, with no spacing in between.
Part B We see the verbatim string literal syntax. It escapes characters differently than other string literals.
String Literal
Part C We call Match on the Regex we created. This returns a Match object. We extract the capture from this object.
Note It is important to use the 1-based Groups syntax: the groups are indexed starting at 1, not 0.
C# program that uses Match Groups
using System; using System.Text.RegularExpressions; class Program { static void Main() { // Part A: the input string we are using. string input = "a45"; // Part B: the regular expression we use to match. Regex regex = new Regex(@"a(\d)(\d)"); // Part C: match the input and write results. Match match = r1.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
Named group. 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.
Here The input string has the number 12345 in the middle of two strings. We match this in a named group called "middle."
C# program that uses named group
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); } // Done. Console.ReadLine(); } }
Middle: 12345
Between, before, after. Regular expressions are not needed for simple parsing tasks. Consider a specialized method that can access strings between, before and after other strings.
Between, Before, After
A summary. You can find a string between two delimiters of multiple characters. With Groups, we can access "captured" values with an int or string.
© 2007-2021 sam allen. see site info on the changelog