rubyregexruby-1.9.3

What are the differences between lazy, greedy and possessive quantifiers?


How do the following quantifiers differ - with respect of scenarios, speed, etc.


Can anyone help me to understand what these terms mean? Why are there three variations of each quantifier for the same job?


Solution

  • Take the string

    aaaab
    

    and see how the following regexes match it:

    Regex          Submatches
                   group 1  group 2  group3
    (a?)(a*)(ab)   a        aa       ab
    (a??)(a*)(ab)           aaa      ab
    (a?+)(a*)(ab)  a        aa       ab
    (a*)(a?)(ab)   aaa               ab
    (a*?)(a?)(ab)  aa       a        ab
    (a*+)(a?)(ab)  aaaa              <Match fails!>
    (a+)(a*)(ab)   aaa               ab 
    (a+?)(a*)(ab)  a        aa       ab
    (a++)(a*)(ab)  aaaa              <Match fails!>
    

    Explanation: