Thanks to everyone.

It seems that the following code does what I want:

#!perl -w my $test = ( "olive&(popeye|bluto)", "(tom&jerry)|(sylvester&tweety)", "moe&(shemp|curly|joe)&larry", "tom&jerry|sylvester&tweety", # valid "moe ( shemp | curly | joe ) larry", # also valid "moe(&shemp|curly|joe)&larry", # invalid: "(&" instead of "&(" "moe ( shemp | curly | joe", # invalid: missing ")" raises an error )[(shift) - 1]; my $expr = $test; $expr =~ s/(\w+)/"(?=.*\\b($1)\\b)"/ge; $expr =~ s/[\&\s]//g; $expr = "^($expr)"; print "$test\n$expr\n----\n"; while (<DATA>) { print $_ if /$expr/; } __DATA__ tom,jerry jerry,tom jerry,tomas sylvester,tweety tweeter,sylvester tom,sylvester popeye,olive olive,brutus moe,larry shemp,curly,joe larry,moe larry,curly,moe
>re.pl 1 olive&(popeye|bluto) ^((?=.*\b(olive)\b)((?=.*\b(popeye)\b)|(?=.*\b(bluto)\b))) ---- popeye,olive >re.pl 2 (tom&jerry)|(sylvester&tweety) ^(((?=.*\b(tom)\b)(?=.*\b(jerry)\b))|((?=.*\b(sylvester)\b)(?=.*\b(twe +ety)\b))) ---- tom,jerry jerry,tom sylvester,tweety >re.pl 3 moe&(shemp|curly|joe)&larry ^((?=.*\b(moe)\b)((?=.*\b(shemp)\b)|(?=.*\b(curly)\b)|(?=.*\b(joe)\b)) +(?=.*\b(larry)\b)) ---- larry,curly,moe

I know this will raise an error if the expression is invalid, but I'm sure it could be checked first with something "simple" like the following:

die "Invalid expression <$test>\n" if $test =~ /[^a-z\s\&\|\(\)]|^\s*[\&\|]|[\&\|]\s*$|[\&\|]\s*[\&\|]| +[\&\|]\s*\)|\(\s*[\|\&]/;

and I'm sure I can find something more to validate that parenthesis are well paired.


In reply to Re: AND and OR on Regular Expressions by vitoco
in thread AND and OR on Regular Expressions by vitoco

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.