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


in reply to Invert grep match with qr// variable

It is possible to put the inversion in the regexp, but I don't recommend it: it will in almost all cases be much less efficient.

Here's how it works: $string =~ /$re/ matches if $re matches at any point in the string; $string =~ /(?!$re)/ matches if there is any point in the string that does not match $re; $string =~ /^(?!.*$re)/s therefore matches only if there is no point in the string that matches $re, and is therefore the inverse.

Inverting outside the pattern just requires one of a couple of ways to ensure the interpreter knows it should do a pattern match:

grep !/$re/, @array; # use // round $re to treat as a pattern match grep $_ !~ $re, @array; # use a negating match

Note that if $re is a precompiled regexp, perl won't need to recompile it just because you put // round it.

Hugo

Replies are listed 'Best First'.
Re^2: Invert grep match with qr// variable
by ikegami (Patriarch) on Feb 06, 2024 at 22:15 UTC
    • .* should be (?s:.*?).
      • Without /s, it could affect whether some strings match or not.
      • Without the non-greedy, it will affect the value of capture vars ($&, $1, etc) on a match. Not relevant in this case.
    • ^ should be be \G
      • This will affect the number of matches when /g is used. Not relevant in this case.
Re^2: Invert grep match with qr// variable
by Dallaylaen (Chaplain) on Feb 07, 2024 at 10:04 UTC
    Cool. Frontpaged the OP for this answer.