liveBook · Manning

Non-greedy quantifier

As explained in The Well-Grounded Rubyist, Fourth Edition

A non-greedy quantifier matches the fewest repetitions needed for the remainder of the regular expression to match.

A question mark after `*` or `+` makes the quantifier non-greedy: it matches the fewest repetitions that still let the rest of the pattern succeed. Unlike a greedy quantifier, it can stop at the first `!` rather than the last. section 11.5.2

Greedy matching is not absolute: the regexp engine can backtrack when needed to make the whole pattern match. For example, `\d+` in `/\d+5/` matches `234`, leaving `5` for the rest of the pattern. section 11.5.2

>> /.+?!/.match(string)[0]
=> "abc!"

Compare this with the greedy `/ .+! /` example: adding `?` makes the match stop at the first exclamation point. section 11.5.2

Matching across lines

In `/\(.*?\)/m`, `.*?` matches the fewest characters through a closing parenthesis; the `m` modifier lets the wildcard match newline characters. section 11.5.4

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Defines `*?` and `+?`, contrasts greedy matching, and explains backtracking with a digit example.
Examples
Demonstrates stopping at the first exclamation point, matching digits, and capturing parenthesized text across newlines.
What you can do after
Apply `*?` or `+?` in Ruby regular expressions to limit a match while satisfying the remaining pattern.
How it connects
Connects greedy quantifiers with backtracking, capture groups, wildcard matching, and regexp modifiers.

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.