fork(1) download
  1. subject = 'Jane"" ""Tarzan12"" Tarzan11@Tarzan22 {4 Tarzan34}'
  2. regex = /{[^}]+}|"Tarzan\d+"|(Tarzan\d+)/
  3. # put Group 1 captures in an array
  4. group1Caps = []
  5. subject.scan(regex) {|m|
  6. group1Caps << $1 if !$1.nil?
  7. }
  8.  
  9. ######## The six main tasks we're likely to have ########
  10.  
  11. # Task 1: Is there a match?
  12. puts("*** Is there a Match? ***")
  13. if group1Caps.length > 0
  14. puts "Yes"
  15. else
  16. puts "No"
  17. end
  18.  
  19. # Task 2: How many matches are there?
  20. puts "\n*** Number of Matches ***"
  21. puts group1Caps.length
  22.  
  23. # Task 3: What is the first match?
  24. puts "\n*** First Match ***"
  25. if group1Caps.length > 0
  26. puts group1Caps[0]
  27. end
  28.  
  29. # Task 4: What are all the matches?
  30. puts "\n*** Matches ***"
  31. if group1Caps.length > 0
  32. group1Caps.each { |x| puts x }
  33. end
  34.  
  35. # Task 5: Replace the matches
  36. replaced = subject.gsub(regex) {|m|
  37. if $1.nil?
  38. m
  39. else
  40. "Superman"
  41. end
  42. }
  43. puts "\n*** Replacements ***"
  44. puts replaced
  45.  
  46. # Task 6: Split
  47. # Start by replacing by something distinctive,
  48. # as in Step 5. Then split.
  49. splits = replaced.split(/Superman/)
  50. puts "\n*** Splits ***"
  51. splits.each { |x| puts x }
  52.  
Success #stdin #stdout 0.01s 7464KB
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}