11.4. Matching, substring captures, and MatchData

So far, we’ve looked at basic match operations:

regex.match(string)
string.match(regex)

These are essentially true/false tests: either there’s a match or there isn’t. Now we’ll examine what happens on successful and unsuccessful matches and what a match operation can do for you beyond the yes/no answer.

11.4.1. Capturing submatches with parentheses

One of the most important techniques of regexp construction is the use of parentheses to specify captures.

The idea is this. When you test for a match between a string—say, a line from a file—and a pattern, it’s usually because you want to do something with the string or, more commonly, with part of the string. The capture notation allows you to isolate ...

Get The Well-Grounded Rubyist, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.