Previous

Next


05. Quantifiers are greedy

  • Let's look at the second rule now - what exactly does this mean?
  • It means that when something being affected by a quantifier can match, it matches as much as it possibly can.
  • Here's a simple example. In the following text:
      This is a boring sentence
    
    the regex:
      This?
    
    will match:
      This
    
  • Note that the "?" quantifer allows the regex portion it modifies (in this case the literal character "s") to match zero or one times - or, if you like, it makes the "s" character optional in this regex. So, in theory, the regex could have matched just:
      Thi
    
  • However, this isn't what happens, because the "?" quantifier is greedy, and it matches the maximum possible amount it can.
  • This is not to say that the "?" can't match zero number of times - it can, but it will only do this if matching would mean that the regex would be unsuccessful.

Previous

Next

Andrew Hill

For LinuxSA Meeting, 17 April 2001