Previous

Next


28. Perl Options - Modifying Greediness

  • Pesky greediness! It's always taking up all the characters, and only backtracking when it has to. What a pain - there's all these regexes that I need to write where I know that:
    1. I only want to match the minimum number of characters to make the match successful.
    2. I know that only one match is going to work - but if it didn't have to do all that backtracking, it would run so much faster!
  • Well, fear not! For Perl has support for minimal, or lazy, quantifiers!
      *?
      +?
      ??
      {min, max}?
    
  • For example:
      #!/usr/bin/perl
      $_ = "* This isn't fantastic, let's drink fanta!";
      if (m/fanta(.*)n/) {
        print "$1\n";
      }
      if (m/fanta(.*?)n/) {
        print "$1\n";
      }
    
    gives:
      stic, let's drink fa
      stic, let's dri
    

Previous

Next

Andrew Hill

For LinuxSA Meeting, 17 April 2001