// ... 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); Console.WriteLine(match.Name); } // Done. Console.ReadLine();
Match
Name
Group
Match Class (System.Text.RegularExpressions) | Microsoft Docs[^]: The Match instance itself is equivalent to the first object in the collection, at Match.Groups[0], which represents the entire match.
Match.Groups[0]
0
$0
Regex expression = new Regex(@"(?<a>abc)|(?<b>def)|(?<c>ghi)", RegexOptions.ExplicitCapture); Match match = expression.Match(input); if (match.Success) { if (match.Groups["a"].Success) { // Matched first option... } else if (match.Groups["b"].Success) { // Matched second option... } else if (match.Groups["c"].Success) { // Matched third option... } }
\K
string input = "2010 1999 1861 2140 2009"; string pattern = @"(?<=\b20)\d{2}\b"; foreach (Match match in Regex.Matches(input, pattern)) { Console.WriteLine(match.Value); } /* Output: 10 09 */
Console.WriteLine(match.Groups[1].Name);
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)