in reply to negate pattern match

You need a look ahead assertion. In this case a negative look ahead assertion (?!to\b|from\b):

use strict; use warnings; while (<DATA>) { print "Matched $_" if /train times (?!to\b|from\b)\w/; } __DATA__ train times to xyz train times from xyz train times including xyz train times tomorrow xyz

Prints:

Matched train times including xyz Matched train times tomorrow xyz

Update: fixed missing \b bug


DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: negate pattern match
by Anonymous Monk on Jan 31, 2006 at 14:14 UTC
    Actually this brings me to another question along the same lines which is...if I wanted to (as I do) check for records where there may be a keyword before "train times" that may mean the record is to be rejected i.e. a negative lookbehind assertion I assume
    e.g.
    help train times from xyz load train times including xyz help train times including xyz book train times at 1234
    I need to reject records where the word immediately before "train times" is help. If help is used in the text it would always be the first word in the record. So only record two & four in my example would be printed. I tried doing this
    print if /(?<!help).*train times/; #doesn't work print if /^(!help).*train times/; # doesn't work either
    Based on other comments I've read it seems that the use of negative lookbehind assertion should be discouraged but I'm not sure how to handle this without doing an assertion ?

      A negative look ahead assertion at the start of the line (not a look back) is what you want:

      use strict; use warnings; while (<DATA>) { print "Matched: $_" if /^(?!help).*?train times (?!to\b|from\b)\w/; } __DATA__ help train times from xyz load train times including xyz help train times including xyz book train times at 1234

      Prints:

      Matched: load train times including xyz Matched: book train times at 1234

      DWIM is Perl's answer to Gödel
        Thanks. I never realised how much there are to ascertians !
Re^2: negate pattern match
by Anonymous Monk on Jan 31, 2006 at 10:00 UTC
    One happy customer, thank you