fork(13) download
  1. using System;
  2. using System.Text.RegularExpressions;
  3. using System.Collections.Specialized;
  4. class Program {
  5. static void Main() {
  6. string s1 = @"apple:green:3 banana:yellow:5";
  7. var myRegex = new Regex(@"(\w+):(\w+):(\d+)");
  8.  
  9. ///////// The six main tasks we're likely to have ////////
  10.  
  11. // Task 1: Is there a match?
  12. Console.WriteLine("*** Is there a Match? ***");
  13. if (myRegex.IsMatch(s1)) Console.WriteLine("Yes");
  14. else Console.WriteLine("No");
  15.  
  16. // Task 2: How many matches are there?
  17. MatchCollection AllMatches = myRegex.Matches(s1);
  18. Console.WriteLine("\n" + "*** Number of Matches ***");
  19. Console.WriteLine(AllMatches.Count);
  20.  
  21. // Task 3: What is the first match?
  22. Console.WriteLine("\n" + "*** First Match ***");
  23. Match OneMatch = myRegex.Match(s1);
  24. if (OneMatch.Success) {
  25. Console.WriteLine("Overall Match: "+ OneMatch.Groups[0].Value);
  26. Console.WriteLine("Group 1: " + OneMatch.Groups[1].Value);
  27. Console.WriteLine("Group 2: " + OneMatch.Groups[2].Value);
  28. Console.WriteLine("Group 3: " + OneMatch.Groups[3].Value);
  29. }
  30.  
  31. // Task 4: What are all the matches?
  32. Console.WriteLine("\n" + "*** Matches ***");
  33. if (AllMatches.Count > 0) {
  34. foreach (Match SomeMatch in AllMatches) {
  35. Console.WriteLine("Overall Match: " + SomeMatch.Groups[0].Value);
  36. Console.WriteLine("Group 1: " + SomeMatch.Groups[1].Value);
  37. Console.WriteLine("Group 2: " + SomeMatch.Groups[2].Value);
  38. Console.WriteLine("Group 3: " + SomeMatch.Groups[3].Value);
  39. }
  40. }
  41.  
  42. // Task 5: Replace the matches
  43. // simple replacement: reverse groups
  44. string replaced = myRegex.Replace(s1,
  45. delegate(Match m) {
  46. return m.Groups[3].Value + ":" +
  47. m.Groups[2].Value + ":" +
  48. m.Groups[1].Value;
  49. }
  50. );
  51. Console.WriteLine("\n" + "*** Replacements ***");
  52. Console.WriteLine(replaced);
  53.  
  54. // Task 6: Split
  55. // Let's split at colons or spaces
  56. string[] splits = Regex.Split(s1, @":|\s");
  57. Console.WriteLine("\n" + "*** Splits ***");
  58. foreach (string split in splits) Console.WriteLine(split);
  59.  
  60. Console.WriteLine("\nPress Any Key to Exit.");
  61. Console.ReadKey();
  62.  
  63. } // END Main
  64. } // END Program
Success #stdin #stdout 0.07s 34144KB
stdin
Standard input is empty
stdout
*** Is there a Match? ***
Yes

*** Number of Matches ***
2

*** First Match ***
Overall Match: apple:green:3
Group 1: apple
Group 2: green
Group 3: 3

*** Matches ***
Overall Match: apple:green:3
Group 1: apple
Group 2: green
Group 3: 3
Overall Match: banana:yellow:5
Group 1: banana
Group 2: yellow
Group 3: 5

*** Replacements ***
3:green:apple 5:yellow:banana

*** Splits ***
apple
green
3
banana
yellow
5

Press Any Key to Exit.