perlpal has asked for the wisdom of the Perl Monks concerning the following question:

Hi PerlMonks,
I have a string $str. It should contain substrings ‘abc’, ‘pqr’ and ‘xyz’. Order of the substrings does not matter. Is there a regular expression that does this check one-time?
I don’t want to write 3 if conditions i.e if( $str =~ /abc/ && $str =~ /pqr/ && $str =~ /xyz/ ).
Thanks in advance!

Replies are listed 'Best First'.
Re: Single string pattern match
by BrowserUk (Patriarch) on Jan 13, 2011 at 11:56 UTC

    Possible, but better?

    /(?=^.*abc)(?=^.*pqr)(?=^.*xyz)/ and print "$_:matched" for qw[ abcpqrxyz xyzpqrabc pqrxyzabc abpqrxyz];; abcpqrxyz:matched xyzpqrabc:matched pqrxyzabc:matched

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Single string pattern match
by JavaFan (Canon) on Jan 13, 2011 at 14:23 UTC
    I don’t want to write 3 if conditions
    Why not? It's simpler, and likely to be more efficient than the look ahead solution.

    But say you want to look for substrings foo, bar and oba. Should foobar be a valid match? It contains all three substrings, but not without overlap.

Re: Single string pattern match
by raybies (Chaplain) on Jan 13, 2011 at 12:59 UTC
     if ($str =~ /((abc)|(pqr)|(xyz))/) $1 would contain first pattern that matches. (update: added external () to make $1 work)