http://www.perlmonks.org?node_id=588329


in reply to Negating Regexes: Tips, Tools, And Tricks Of The Trade

I was experimenting with this and came up with the following .
use strict; use warnings; my $pattern = qr/abc/; my $negative = qr< (??{ /$pattern/ ? qr/\A$/ : qr//; }) >x; my $text = 'abcdef'; if ($text =~ /$negative/) { print "matched $text\n"; }
This strategy uses (??{ code }) to evaluate the current string against the regex you wish to negate.
If the pattern matches it returns a regex that matches an empty string.
Otherwise it returns a regex that matching anything.

I'm not sure how safe this strategy is though. Can someone who knows more about perl's regex engine comment on whether the above is appropriate?