Firstly, the "all a's" or "all b's" is due to the (a|b) evaluating to an a, or to a b then subsequently being repeated by the +.

A better way to achieve that goal is with a 'character class', where you'd write: /[ab]+/

Regarding matching p.*e.*r.*l, the various solutions so far lack 'data driven'-ness, in that they embed the sought-after characters in code.

An approach which allows the sought-after chars to be specified would be:

my @required_chars = qw/p e r l/; # Or anything else... LINE: while (<>) { foreach my $char (@required_chars) { next LINE unless index($_, $char) >= 0; } print; }
A more insane (and presumably less efficient) way of doing it would be to compile the N sought after characters into a regexp which would match each of the N! ways these chars might occur in the string.
#!perl -w # Warning - silly way of solving problem use strict; # CPAN, how we love thee use Math::Combinatorics; my @required_chars = qw/p e r l/; # Or anything else... # For bonus points, we could create a package which blessed # the regexp into an object. But that would be silly. my $re = make_re(@required_chars); while (<>) { print if /$re/; } sub make_re { # Get all N! ways of arranging the chars my @combinations = permute(@_); # Construct a.*b.*.*d strings, for each my @res = map { join(".*", @$_); } @combinations; # Put them together into a honking great regexp my $re = "(" . join("|", @res) . ")"; return qr/$re/; }

In reply to Re: A Quick Regex Question by jbert
in thread A Quick Regex Question by chinamox

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.