fork(6) download
  1. using System;
  2. using System.Text.RegularExpressions;
  3. using System.Collections.Specialized;
  4. class Program
  5. {
  6. static void Main() {
  7. string s1 = @"Jane"" ""Tarzan12"" Tarzan11@Tarzan22 {4 Tarzan34}";
  8. var myRegex = new Regex(@"{[^}]+}|""Tarzan\d+""|(Tarzan\d+)");
  9. var group1Caps = new StringCollection();
  10.  
  11. Match matchResult = myRegex.Match(s1);
  12. // put Group 1 captures in a list
  13. while (matchResult.Success) {
  14. if (matchResult.Groups[1].Value != "") {
  15. group1Caps.Add(matchResult.Groups[1].Value);
  16. }
  17. matchResult = matchResult.NextMatch();
  18. }
  19.  
  20. ///////// The six main tasks we're likely to have ////////
  21.  
  22. // Task 1: Is there a match?
  23. Console.WriteLine("*** Is there a Match? ***");
  24. if(group1Caps.Count>0) Console.WriteLine("Yes");
  25. else Console.WriteLine("No");
  26.  
  27. // Task 2: How many matches are there?
  28. Console.WriteLine("\n" + "*** Number of Matches ***");
  29. Console.WriteLine(group1Caps.Count);
  30.  
  31. // Task 3: What is the first match?
  32. Console.WriteLine("\n" + "*** First Match ***");
  33. if(group1Caps.Count>0) Console.WriteLine(group1Caps[0]);
  34.  
  35. // Task 4: What are all the matches?
  36. Console.WriteLine("\n" + "*** Matches ***");
  37. if (group1Caps.Count > 0) {
  38. foreach (string match in group1Caps) Console.WriteLine(match);
  39. }
  40.  
  41. // Task 5: Replace the matches
  42. string replaced = myRegex.Replace(s1, delegate(Match m) {
  43. // m.Value is the same as m.Groups[0].Value
  44. if (m.Groups[1].Value == "") return m.Value;
  45. else return "Superman";
  46. });
  47. Console.WriteLine("\n" + "*** Replacements ***");
  48. Console.WriteLine(replaced);
  49.  
  50. // Task 6: Split
  51. // Start by replacing by something distinctive,
  52. // as in Step 5. Then split.
  53. string[] splits = Regex.Split(replaced,"Superman");
  54. Console.WriteLine("\n" + "*** Splits ***");
  55. foreach (string split in splits) Console.WriteLine(split);
  56.  
  57. Console.WriteLine("\nPress Any Key to Exit.");
  58. Console.ReadKey();
  59.  
  60. } // END Main
  61. } // END Program
Success #stdin #stdout 0.08s 34176KB
stdin
Standard input is empty
stdout
*** 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.