Try `/abc/.match("The alphabet starts with abc.")`: Ruby returns a MatchData object containing the match. Try the same pattern against `"def"`, and the result is `nil`. Use `match` when you need details about a match, rather than just the true-or-false answer from `match?` or the starting index from `=~`. section 11.2.2
Save a successful result before querying it: `m = pattern.match(string)`. Then `m.string` gives the original string, `m[0]` gives the whole matched substring, and `m.captures` gives the substrings matched by parenthesized groups. Individual captures are also available as `m[1]`, `m[2]`, and so on. Check for `nil` before calling these methods. section 11.4.2
Capture a name and title
`/([A-Za-z]+),[A-Za-z]+,(Mrs?\.)/.match("Peel,Emma,Mrs.,talented amateur")` returns a MatchData object whose first capture is `"Peel"` and second is `"Mrs."`. Parentheses select the parts to retrieve; the entire matched portion remains available at index `0`. section 11.4.1 section 11.4.2
Listing 11.1 Matching a phone number and querying the resulting MatchData object
string = "My phone number is (123) 555-1234."
phone_re = %r{\((\d{3})\)\s+(\d{3})-(\d{4})}
m = phone_re.match(string)
unless m
puts "There was no match—sorry."
exit #1
end
print "The whole string we started with: "
puts m.string 1
print "The entire part of the string that matched: "
puts m[0] 2
puts "The three captures: "
3.times do |index| 3
puts "Capture ##{index + 1}: #{m.captures[index]}"
end
puts "Here's another way to get at the first capture:"
print "Capture #1: "
puts m[1] 4
The phone-number example checks for failure, then retrieves the original string, full match, and three captures through both `captures` and numbered indexing. section 11.4.2
For context around a match, `pre_match` and `post_match` return the portions before and after it. `begin(n)` and `end(n)` give the positions of capture `n`. Ruby also sets `$~` to the MatchData object after a successful `match` or `=~` operation, and to `nil` after failure; keeping a local result makes it straightforward to inspect the match you just tested. section 11.4.4 section 6.1.2
