liveBook · Manning

Greedy matching

As explained in The Well-Grounded Rubyist, Fourth Edition

A greedy quantifier matches as many repetitions as possible while still allowing the remainder of the regular expression to match.

A greedy quantifier consumes as many repetitions as possible while still leaving enough of the string for the rest of the regular expression to match. In Ruby, both * and + are greedy by default. section 11.5.1 section 11.5.2

Stopping at the last delimiter

Given string = "abc!def!ghi!", /. +!/ without the space matches "abc!def!ghi!" because + consumes as much as possible before the final !. Writing /.+?!/ makes + non-greedy, producing "abc!" instead. section 11.5.2

Greedy matching follows these mechanics:

  • The engine initially lets a quantifier consume as much as it can. section 11.5.1
  • Greediness remains subordinate to the complete pattern: if the remainder cannot match, the engine backtracks and gives characters back. section 11.5.2
  • Appending ? to * or + makes the quantifier non-greedy, so it takes only as much as needed for the remainder to match. section 11.5.2
>> /(\d+)(5)/.match("Digits-R-Us 2345")
=> #<MatchData "2345" 1:"234" 2:"5">

Inspect MatchData to see how greedy digit consumption gives back the final digit so the following 5 can match. section 11.5.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains default greediness, lazy modifiers, captures, and backtracking, stopping short of broader regexp-engine implementation.
Examples
Demonstrates digit runs, exclamation-delimited strings, and MatchData captures showing backtracking.
What it assumes
Assumes basic regular-expression syntax and teaches quantifier greediness and backtracking through concrete matches.
What you can do after
Diagnose regexp matches by predicting greedy consumption, applying lazy modifiers, and inspecting captures after backtracking.
How it connects
Connects quantifiers with regular expressions, non-greedy matching, capture groups, and backtracking.

Also explained in

Compare how 2 books explain greedy matching →

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.