LanX has asked for the wisdom of the Perl Monks concerning the following question:
I'm using the regex engine to identify delimited fields matching certain conditions.
Thanks to Perl's internal trie optimization of OR-conditions¹ it's far faster than using LIKE in mysql especially with hundreds of patterns to check
$text = 'A0 peter Z0 ... A42 peter, paul and mary Z42 ... A99 mary Z9 +9'; my @or_matches = ( $text =~ m/A(\d+)[^Z]*(peter|mary)[^Z]*Z/g ); print "@or_matches \n"; __END__ 0 peter 42 mary 99 mary
But now I got the requirement to find fields which match multiple regex at the same time ... and AFAIK the regex grammar doesn't have an AND operator
The best guess I have is using zero-look-ahead assertions:
$text = 'A0 peter Z0 ... A42 peter, paul and mary Z42 ... A99 mary Z9 +9'; my @and_matches =( $text =~ m/ A(\d+)[^Z]* ( (?=mary) [^Z]* peter | (?=peter) [^Z]* mary ) [^Z]*Z /xg ); print "@and_matches \n"; __END__ 42 peter, paul and mary
Well, already rather complicated for just two patterns ... and I doubt that it's fast ... any better suggestions?
Cheers Rolf
Ok the following is already much better since it avoids or-chaining all possible orders of patterns just by anchoring the look-ahead at field-start.
Footnotes:print @and_matches =( $text =~ m/ A(\d+) ( (?= [^Z]* mary ) (?= [^Z]* peter ) [^Z]* ) Z\1 /xg );
¹) >5.10 IIRC
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: realizing AND in regex?
by BillKSmith (Monsignor) on Sep 13, 2012 at 12:26 UTC | |
by LanX (Saint) on Sep 13, 2012 at 13:02 UTC | |
by AnomalousMonk (Archbishop) on Sep 13, 2012 at 17:36 UTC | |
by LanX (Saint) on Sep 13, 2012 at 18:38 UTC | |
|
Re: realizing AND in regex?
by pvaldes (Chaplain) on Sep 13, 2012 at 22:39 UTC |