Greedy Matching

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 cat

You can control the greediness of pattern matching to do things such as process directory paths (here matching on the character):

greedy2.rb

puts( /.+\/.match('C:mydirectorymyfoldermyfile.txt') )
    #=> C:mydirectorymyfolder
puts( /.+?\/.match('C:mydirectorymyfoldermyfile.txt') )
    #=> C:
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.60.158