Perl Regex: Negative lookaheads

Viewed 451

I have this test text:

cake/app/webroot/js/compiled/shop.js
cake/app/webroot/js/compiled/shop.min.js
cake/app/webroot/js/good/thing.js

When I try this:

/^(?!.*compiled)(?!.*min).*$/

It doesn't match anything. But when I add:

/^.*

to the beginning, it matches something on each line. (I only want the last line matched.)

What am I missing?

1 Answers

Your first regex matches the third line

my $re = qr/^(?!.*compiled)(?!.*min).*$/;
while(<DATA>) {
    chomp;
    if (/$re/) {
        say 'OK : ', $_;
    } else {
        say 'KO';
    }
}


__DATA__
cake/app/webroot/js/compiled/shop.js
cake/app/webroot/js/compiled/shop.min.js
cake/app/webroot/js/good/thing.js

Output:

KO
KO
OK : cake/app/webroot/js/good/thing.js

When you add .* at the beginning, it matches the whole line then the negative lookahead is true, there is no compiled or min after the regex has consume all the characters, so the match is true.

Related