Suppose I want to match the occurrence of 4 characters
in a string with the condition that all 4 must occur at least once and in any order.
Well, with a regex engine that implements greedy alternation
I could have one single regex such as this egrep example:
$ echo 1b22a3d3c | egrep -o 'a|b|c|d'
b
a
d
c
But with perl(no greedy alternation) I would need to construct a large-ish if statement
echo 1b22a3d3c | perl -ne'if(/a/&&/b/&&/c/&&/d/){print"Match!\n";}'
If I am curious about in which order the 4 chars actually occurred in I can test each permutation using List::Permutor
use strict;
use warnings;
use List::Permutor;
my $test_string="1b22a3d3c";
my @regex_parts=("a","b","c","d");
my $permutated_regex_parts=new List::Permutor @regex_parts;
while (my @set = $permutated_regex_parts->next){
my $pattern=construct_regex(@set);
if($test_string =~ /$pattern/){
print("a match! pattern is: $pattern\n");
}
}
sub construct_regex{
my $regex=".*";
foreach my $s (@_){
$regex.="$s.*";
}
return $regex;
}
I have toyed with this problem a bit...I am sure I missed several possible insights into better/shorter ways to accomplish this. Any advice?
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.