liveBook · Manning

MatchData#captures

As explained in The Well-Grounded Rubyist, Fourth Edition

MatchData#captures returns an array of the substrings captured by the regular expression's parenthesized capture groups.

MatchData#captures returns an array containing the substrings matched by a regular expression’s parenthesized capture groups. For a phone-number match, the array contains "123", "555", and "1234". section 11.4.2

Extracting phone-number parts

phone_re = %r{\((\d{3})\)\s+(\d{3})-(\d{4})} m = phone_re.match("My phone number is (123) 555-1234.") m.captures # => ["123", "555", "1234"] The array is zero-based, so m.captures[0] is the first capture. section 11.4.3

Use captures alongside MatchData indexing when extracting or interpreting matched substrings:

  • m[0] returns the entire matched substring; m[1] returns the first parenthesized capture. section 11.4.2
  • m[1] == m.captures[0] and m[2] == m.captures[1]; indexing MatchData counts captures from 1, while the returned array counts from 0. section 11.4.3
  • Capture numbers follow opening parentheses from left to right, including nested groups; negative MatchData indexes retrieve captures from the end. section 11.4.3

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains the returned array, zero-based indexing, capture numbering, nesting, and contrasts with MatchData indexing.
Examples
Uses a traditional U.S. phone number and nested alphabetic groups to demonstrate captured values and their numbering.
What it assumes
Assumes familiarity with Ruby regular-expression matching and MatchData while clarifying capture numbering from concrete examples.
What you can do after
Apply captures to retrieve all parenthesized substrings from a successful MatchData object as a regular Ruby array.
How it connects
Connects captures with regular expressions, MatchData, capture groups, named captures, and match-result indexing.

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.