in reply to AND and OR on Regular Expressions

The match op looks for a series of patterns one after the other. It doesn't look at the big picture. It can do "or" easy because it simply checks "Is A or B at this spot?". However, that's not possible with "and". "Are A and B at this spot?" is not what you want.

There are tricks to make the regex match search the string multiple times, each with a different pattern

/^(?=.*?pat1)(?=.*?pat2)...(?=.*?patNm1)(?=.*?patN)/
/^(?=.*?pat1)(?=.*?pat2)...(?=.*?patNm1).*?patN/

but those are really just poorly readable versions of

/pat1/ && /pat2/ && ... && /patNm1/ && /patN/

Checking if a section of the string contains matches two patterns is much harder.

Replies are listed 'Best First'.
Re^2: AND and OR on Regular Expressions
by JavaFan (Canon) on Aug 25, 2009 at 15:55 UTC
    There's no reason to use '.*?' instead of '.*' in your examples - a pattern that will match with '.*?' will match with '.*' as well. But '.*?' can be significantly slower than '.*'. I prefer to avoid '.*?' if '.*' will do.

    Note that the "one regexp" is still useful - you can pass in a single regexp to a function, 'qr' it, pass it in a webform, or store it in a configuration file which you usually cannot do with the && chained ones.

      There's no reason to use '.*?' instead of '.*' in your examplesl.

      It matters if the pattern contain captures.

      I must admit I approached my post backwards. I started with /pat1/ && /pat2/ and gave the functionally equivalent pattern. (Well, /.*?/ should actually be /(?s:.)*?/)

        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.