in reply to Regex negative word

Of course, there are several ways to "skin a cat" (sorry :D)

Update: just acknowledging the fact that (as has been pointed out) this solution doesn't actually work. I won't bother changing the code, but rather leave it there as an example of how _not_ to do it ;)

#!/usr/bin/perl -wl use strict; while (<DATA>) { chomp; print "$_ matched" if /^[^(?:cat)]/; } __DATA__ cat dog dog cat frog cat dog mouse dog cat cat dog elephant
Prints:
dog cat matched frog cat dog matched mouse dog cat matched
Cheers,
Darren :)

Replies are listed 'Best First'.
Re^2: Regex negative word
by GrandFather (Saint) on Mar 30, 2006 at 04:13 UTC

    That is not doing what you think. Consider:

    use strict; use warnings; while (<DATA>) { print "matched $_" if /^[^cat)(?:]/; } __DATA__ cat dog dog cat aardvark ant catnip dogbone frog cat dog mouse dog cat cat dog elephant can of worms

    Prints:

    matched dog cat matched frog cat dog matched mouse dog cat

    The following code excludes beginning cats and insists that dogs end:

    use strict; use warnings; while (<DATA>) { print "matched $_" if /^(?!cat\b).*(?=\bdog$)/; } __DATA__ cat dog dog cat catnip dogbone aardvark ant frog cat dog can of worms

    Prints:

    matched frog cat dog

    DWIM is Perl's answer to Gödel
Re^2: Regex negative word
by pKai (Priest) on Mar 30, 2006 at 06:51 UTC
    McDarren,

    your codes fails, because there is no such thing as complex grouping inside character classes (apart form ranges denoted by -). So especially your (?:cat) in there is not a single entity saying "c followed by a followed by t", but refers to the 7 characters it consists of.

    Grandfather saw this, but obscured the point in his reply somewhat by reordering that 7 chars. But you can use your code with his __DATA__ and still see that lines beginning with "a" or any "c" (not only that reading "cat") will yield no match!

    The way to solve the problem of the OP is to use look-ahead-assertions, as demonstrated by Grandfather in both his replies.

Re^2: Regex negative word
by zer (Deacon) on Mar 30, 2006 at 03:44 UTC
    this works!