July 2011
Intermediate to advanced
400 pages
8h 46m
English
When a string contains more than one potential match, you may sometimes want to return the string up to the first match (that is, as little of the string as possible consistent with the match pattern), and at other times you may want the string up to the last match (that is, as much of the string as possible).
In the latter case (getting as much of the string as possible), the match is said to be greedy. The * and + pattern quantifiers are greedy. However, you can put them on a diet, to make them return the least possible, by putting ? after them:
greedy1.rb
puts( /.*at/.match('The cat sat on the mat!') ) #=> The cat sat on the mat
puts( /.*?at/.match('The cat sat on the mat!') ) #=> The catYou can control the greediness of pattern ...
Read now
Unlock full access