I missed the '2 or 3' requirement on first reading of the OP. For the sake of maintainability if nothing else, a looping (loopy?) approach may, as you say, be the way to go.

However, there is a simple way to deal with the undefined values produced by zero-quantified captures:

>perl -wMstrict -le "my $bound = qr{ (?<! [\w-]) }xms; my $A = qr{ (?= .* $bound A \s+ (\w+)) }xms; my $B = qr{ (?= .* $bound B \s+ (\w+)) }xms; my $C = qr{ (?= .* $bound C \s+ (\w+)) }xms; my $extract = qr{ \A $A? $B? $C? }xms; print '-------------------'; for my $line (@ARGV) { my $s = join '_', my @got = grep defined, $line =~ $extract; $s = 'no match' if @got < 2 or @got > 3; print qq{'$line': '$s'}; } " "B Bee C Cee A Aye" "foo C Cee bar A Aye baz B Bee zzz" "A Aye B Bee +" "C Cee foo B Bee" "xxx C Chuck yyyy A Able zzz" "A Aye A Aye B Bee" foo "A Aye" "A Aye pseudo-B Bee" "A Aye XYZB Bee" "A Aye A Aye A A +ye" ------------------- 'B Bee C Cee A Aye': 'Aye_Bee_Cee' 'foo C Cee bar A Aye baz B Bee zzz': 'Aye_Bee_Cee' 'A Aye B Bee': 'Aye_Bee' 'C Cee foo B Bee': 'Bee_Cee' 'xxx C Chuck yyyy A Able zzz': 'Able_Chuck' 'A Aye A Aye B Bee': 'Aye_Bee' 'foo': 'no match' 'A Aye': 'no match' 'A Aye pseudo-B Bee': 'no match' 'A Aye XYZB Bee': 'no match' 'A Aye A Aye A Aye': 'no match'

In reply to Re^4: Need a Regular Expression that tests for words in different order and captures the values found. by AnomalousMonk
in thread Need a Regular Expression that tests for words in different order and captures the values found. by greatwazzoo

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.