using System;
using System.Text.RegularExpressions;
class Program {
static void Main() {
string ourString = @"Italian:one=uno,two=due Japanese:one=ichi,two=ni,three=san";
string ourPattern = @"\w+:(?:(\w+)=(\w+),?)+";
var ourRegex = new Regex(ourPattern);
MatchCollection AllMatches = ourRegex.Matches(ourString);
Console.WriteLine("**** Understanding .NET Capture Groups with Quantifiers ****");
Console.WriteLine("\nOur string today is:" + ourString);
Console.WriteLine("Our regex today is:" + ourPattern);
Console.WriteLine("Number of Matches: " + AllMatches.Count);
Console.WriteLine("\n*** Let's Iterate Through the Matches ***");
int matchNum = 1;
foreach (Match SomeMatch in AllMatches) {
Console.WriteLine("Match number: " + matchNum++);
Console.WriteLine("Overall Match: " + SomeMatch.Value);
Console.WriteLine("\nNumber of Groups: " + SomeMatch.Groups.Count);
Console.WriteLine("Why three Groups, not two? Because the overall match is Group 0");
// Another way of printing the overall match
Console.WriteLine("Group 0: " + SomeMatch.Groups[0].Value);
Console.WriteLine("Since Groups 1 and 2 have quantifiers, the value of Group 1 and Group 2 is the last capture of each group");
Console.WriteLine("Group 1: " + SomeMatch.Groups[1].Value);
Console.WriteLine("Group 2: " + SomeMatch.Groups[2].Value);
// For this match, let's look all the Group 1 captures manually
int g1capCount = SomeMatch.Groups[1].Captures.Count;
Console.WriteLine("Number of Group 1 Captures: " + g1capCount);
Console.WriteLine("Group 1 Capture 0: " + SomeMatch.Groups[1].Captures[0].Value);
Console.WriteLine("Group 1 Capture 1: " + SomeMatch.Groups[1].Captures[1].Value);
// To be safe, we'll check if we have a third capture for Group 1
// Because the first overall match only has two captures
if(g1capCount>2) Console.WriteLine("Group 1 Capture 2: " + SomeMatch.Groups[1].Captures[2].Value);
// Let's look at Group 2 captures automatically
int g2capCount = SomeMatch.Groups[2].Captures.Count;
Console.WriteLine("Number of Group 2 Captures: " + g2capCount);
int i2 = 0;
foreach (Capture g2capture in SomeMatch.Groups[2].Captures ) {
Console.WriteLine("Group 2 Capture " + i2 + ": " + g2capture.Value);
i2++;
} // end iterate G2 captures
Console.WriteLine("\n");
} // end iterate matches
Console.WriteLine("\nPress Any Key to Exit.");
Console.ReadKey();
} // END Main
} // END Program