using System; using System.Text.RegularExpressions; class Program { static void Main() { string ourString = @"one-two-three:uno-dos-tres one-two-three:ichi-ni-san"; string ourPattern = @"(?:(?\w+)-?)+:(?:(?\w+)-?)+"; var ourRegex = new Regex(ourPattern); MatchCollection AllMatches = ourRegex.Matches(ourString); Console.WriteLine("**** Understanding Named Capture Reuse ****"); 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 two Groups, not one? Because the overall match is Group 0"); // Another way of printing the overall match Console.WriteLine("Groups[0].Value = " + SomeMatch.Groups[0].Value); Console.WriteLine(@"Since the 'someword' group appears more than once in the pattern, the value of Groups[1] and Groups[""someword""] is the last capture of each group"); Console.WriteLine("Groups[1].Value = " + SomeMatch.Groups[1].Value); Console.WriteLine(@"Groups[""someword""].Value = " + SomeMatch.Groups["someword"].Value); // Let's look all the first captures manually Console.WriteLine("Someword Capture 0: " + SomeMatch.Groups["someword"].Captures[0].Value); // Let's look at someword captures automatically int somewordCapCount = SomeMatch.Groups["someword"].Captures.Count; Console.WriteLine("Number of someword Captures: " + somewordCapCount); int i2 = 0; foreach (Capture someword in SomeMatch.Groups["someword"].Captures) { Console.WriteLine("someword Capture " + i2 + ": " + someword.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