subject = 'Jane"" ""Tarzan12"" Tarzan11@Tarzan22 {4 Tarzan34}'
regex = /{[^}]+}|"Tarzan\d+"|(Tarzan\d+)/
# put Group 1 captures in an array
group1Caps = []
subject.scan(regex) {|m|
group1Caps << $1 if !$1.nil?
}
######## The six main tasks we're likely to have ########
# Task 1: Is there a match?
puts("*** Is there a Match? ***")
if group1Caps.length > 0
puts "Yes"
else
puts "No"
end
# Task 2: How many matches are there?
puts "\n*** Number of Matches ***"
puts group1Caps.length
# Task 3: What is the first match?
puts "\n*** First Match ***"
if group1Caps.length > 0
puts group1Caps[0]
end
# Task 4: What are all the matches?
puts "\n*** Matches ***"
if group1Caps.length > 0
group1Caps.each { |x| puts x }
end
# Task 5: Replace the matches
replaced = subject.gsub(regex) {|m|
if $1.nil?
m
else
"Superman"
end
}
puts "\n*** Replacements ***"
puts replaced
# Task 6: Split
# Start by replacing by something distinctive,
# as in Step 5. Then split.
splits = replaced.split(/Superman/)
puts "\n*** Splits ***"
splits.each { |x| puts x }