in reply to Blacklisting with a Regular Expression
Note that the if condition you had did not match your comments. "Match on any string" generally means you're looking at one string at a time. Of course if you can't modify that code then the comment should change to match.my @blacklist = ('evil', 'bad', 'wrong'); my $a = "this string contains no blacklisted tokens"; my $b = "this string is evil and wrong"; my $regex = join '|', @blacklist; # The !~ is a better way to do !(foo =~ /regex/) if ($a !~ /$regex/) { print "Success with a!\n"; } else { print "Failure with a\n"; } if ($b !~ /$regex/) { print "Success with b!\n"; } else { print "Failure with b\n"; }
Update: Sigh. And looking too much at the "match any string" bit caused me to reverse the logic of what you need. Must think on that a bit more...
Update the second:The problem with negative lookaheads is that it's easy to match when you don't want to. To simplify your problem a bit, just look at the word evil and try to match something without that in the text.
my $regex = '.(?!evil)'; if ("this is so evil" =~ /($regex)/) { print "yay: $1\n"; }
Prints "yay: t" for the simple fact that it matches at the beginning of the string. So you'll get false positives, because you need to check the whole string for the bad token, and negate that. I'd love to see a solution to this regex issue, personally, but I don't know of one.
Honestly I think the solution will not be a regex, but a change in the surrounding code. Even if it is possible to create a regex that does what you need, it's going to be more complex than making a few simple changes to the conditional. Reverse the logic of the if statement, the regex is trivial. Therefore future programmers won't curse your name and all will be happy in the world. Or something.
|
|---|