in reply to A Quick Regex Question

One way to do it is to use tr to count the characters of interest in each word:

use strict; use warnings; my @words = qw(Perl purile pretty reputation reputable); for (@words) { print "Matched $_\n" if tr/pP// && tr/eE// && tr/rR// && tr/lL//; }

Prints:

Matched Perl Matched purile Matched reputable

Note that you have to test seperately for each letter and ensure that at least one of each is present. That is why there are four different tests - one for each letter.

Note too that if you want a case insensitive match both upper and lower case versions of the letter need to be present.


DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: A Quick Regex Question
by eyepopslikeamosquito (Archbishop) on Oct 08, 2006 at 09:00 UTC

    I like Gramp's solution: simple, elegant and efficient. Too often people automatically go for a regex when the good old tr operator is a better choice.

    Due to my unfortunate golfing past, I can't restrain myself from noting that, if you are feeling in a silly mood, you could replace his simple and clear line:

    print "Matched $_\n" if tr/pP// && tr/eE// && tr/rR// && tr/lL//;
    with this silly one:
    y&pP&&&&y&eE&&&&y&rR&&&&y&lL&&&&print"Matched $_\n";
    Deparse confirming their equivalence:
    # cat sensible.pl print "Matched $_\n" if tr/pP// && tr/eE// && tr/rR// && tr/lL//; # perl -MO=Deparse sensible.pl print "Matched $_\n" if tr/Pp// and tr/Ee// and tr/Rr// and tr/Ll//; sensible.pl syntax OK # cat silly.pl y&pP&&&&y&eE&&&&y&rR&&&&y&lL&&&&print"Matched $_\n"; # perl -MO=Deparse silly.pl print "Matched $_\n" if tr/Pp// and tr/Ee// and tr/Rr// and tr/Ll//; silly.pl syntax OK

      Actually compared to the translate (counting) technique, for a case sensitive match McDarren's solution using the equivelent regex technique is slightly faster, but it's slightly slower if using a case insensitive match. Case sensitivity makes no significant difference to the translate.

      For the sake of code clarity I'd actually go with the multiple regex solution, but offered the translate solution because the technique gets forgotten about somewhat.


      DWIM is Perl's answer to Gödel
Re^2: A Quick Regex Question
by chinamox (Scribe) on Oct 09, 2006 at 09:01 UTC

    Smiles... I found && in perldoc yesterday and thought it might be useful. I will certainly make use of it in the very near future. Thank you!

    -mox