in reply to Re^3: AND and OR on Regular Expressions
in thread AND and OR on Regular Expressions

If the patterns contain captures, then
/pat1/ && /pat2/
and
/(?=.*?pat1)(?=.*?pat2)/s
aren't equivalent in the first place.

Note also that the OP didn't specify whether pat1 and pat2 may overlap. /pat1/ && /pat2/ has the potential to match more than /pat1.*pat2|pat2.*pat1/s. All of the presented solutions so far assume it's ok the patterns may overlap.

Replies are listed 'Best First'.
Re^5: AND and OR on Regular Expressions
by ikegami (Patriarch) on Aug 25, 2009 at 21:20 UTC

    aren't equivalent in the first place.

    Aside from the missing leading ^, what do you mean?

    Granted, you need some extra code if you want to know what those captures are, but I don't see how they'll capture something different.

    Or are you simply referring to the renumbering of the variables in backrefs?

      Some examples:
      $_ = "foo bar foo"; $pat1 = "(foo)"; $pat2 = "(bar)"; /$pat1/ && /$pat2/; # Sets $1 (twice). /^(?=.*?$pat1)(?=.*?$pat2)/; # Sets $1 and $2. $pat1 = "(foo)"; $pat2 = "(baz)"; /$pat1/ && /$pat2/; # Sets $1. /^(?=.*?$pat1)(?=.*?$pat2)/; # Doesn't set $1 or $2. $pat1 = "(foo)"; $pat2 = "( )\\g{1}"; /$pat1/ && /$pat2/; # No match. /^(?=.*?$pat1)(?=.*?$pat2)/; # Match!
      As for the leading ^ - it only has a speed influence, and only if there's no match. But it can be a significant speed difference if the string is long, so it's better not to omit it.

        So "yes".

        You're missing the line that initialises $_ to something "foo" for the second block.