Previous

Next


27. Perl Options - Lookahead

  • Perl allows you to look further down the target than where the regex engine is up to, and make decisions on what's coming up without actually using up characters to match this part of the regex.
  • There are two flavours - positive and negative lookahead.
  • Positive lookahead is spcified with the "(?= ... )" construct, and will only match if the pattern specified could match in that position - but it does not actually match.
  • For example:
      #!/usr/bin/perl
      $_ = "A fancy test string that will test out positive lookahead.";
      if (m/test (\w* (?=positive))/) {
        print "$1\n";
      }
    
    gives:
      out 
    
  • Similarly, negative lookahead, specified with "(?! ... )", only matches if the pattern specified does not match, again without actually "consuming" those positions for the non-match.

Previous

Next

Andrew Hill

For LinuxSA Meeting, 17 April 2001