liveBook · Manning

MatchData

As explained in The Well-Grounded Rubyist, Fourth Edition

MatchData is a Ruby object containing the results, captured substrings, and locations associated with a regular-expression match.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Works through failure checks, whole-match and capture retrieval, surrounding text, and capture positions without attempting an exhaustive method reference.
Examples
Uses a name-and-title string and a U.S. phone number to demonstrate captures and MatchData queries.
What it assumes
Assumes basic Ruby strings, method calls, and conditionals while teaching parenthesized regexp captures through examples.
What you can do after
Diagnose/debug with it by checking match failure and inspecting captured substrings, surrounding text, and capture positions.
How it connects
Connects regular expressions, parenthesized captures, conditional assignment, and the `$~` match variable.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.