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

