using System; using System.Text.RegularExpressions; using System.Collections.Specialized; class Program { static void Main() { string s1 = @"Jane"" ""Tarzan12"" Tarzan11@Tarzan22 {4 Tarzan34}"; var myRegex = new Regex(@"{[^}]+}|""Tarzan\d+""|(Tarzan\d+)"); var group1Caps = new StringCollection(); Match matchResult = myRegex.Match(s1); // put Group 1 captures in a list while (matchResult.Success) { if (matchResult.Groups[1].Value != "") { group1Caps.Add(matchResult.Groups[1].Value); } matchResult = matchResult.NextMatch(); } ///////// The six main tasks we're likely to have //////// // Task 1: Is there a match? Console.WriteLine("*** Is there a Match? ***"); if(group1Caps.Count>0) Console.WriteLine("Yes"); else Console.WriteLine("No"); // Task 2: How many matches are there? Console.WriteLine("\n" + "*** Number of Matches ***"); Console.WriteLine(group1Caps.Count); // Task 3: What is the first match? Console.WriteLine("\n" + "*** First Match ***"); if(group1Caps.Count>0) Console.WriteLine(group1Caps[0]); // Task 4: What are all the matches? Console.WriteLine("\n" + "*** Matches ***"); if (group1Caps.Count > 0) { foreach (string match in group1Caps) Console.WriteLine(match); } // Task 5: Replace the matches string replaced = myRegex.Replace(s1, delegate(Match m) { // m.Value is the same as m.Groups[0].Value if (m.Groups[1].Value == "") return m.Value; else return "Superman"; }); Console.WriteLine("\n" + "*** Replacements ***"); Console.WriteLine(replaced); // Task 6: Split // Start by replacing by something distinctive, // as in Step 5. Then split. string[] splits = Regex.Split(replaced,"Superman"); Console.WriteLine("\n" + "*** Splits ***"); foreach (string split in splits) Console.WriteLine(split); Console.WriteLine("\nPress Any Key to Exit."); Console.ReadKey(); } // END Main } // END Program
Standard input is empty
*** Is there a Match? ***
Yes
*** Number of Matches ***
2
*** First Match ***
Tarzan11
*** Matches ***
Tarzan11
Tarzan22
*** Replacements ***
Jane" "Tarzan12" Superman@Superman {4 Tarzan34}
*** Splits ***
Jane" "Tarzan12"
@
{4 Tarzan34}
Press Any Key to Exit.
The brand new service which powers Ideone!
Widget for compiling and running the source code in a web browser!