I agree with previous replies that there is no point to using a 'one big regex' solution when the job can be done more clearly, even if with more statements.

That said, I could not understand why the  $match2 regex would not extract the  b named capture from  $input1 string: there is clearly a  'b=2' substring there to  b extracted.

A little instrumentation made the situation clear. The first  /.*?/ lazy expression and the  /(?<b>b=(\d))?/ lazy capture are immediately satisfied. That leaves the second  /.*?/ lazy expression and the final required expression at the end of the line to match. The second  /.*?/ tries to match with nothing, but then must backtrack (forward-track?) and consume all text (including the  'b=2' substring) until the final required expression matches in order to achieve an overall match.

This is made clear in the following (note the added named capture around the second  /.*?/):

>perl -wMstrict -le "my $input1 = 'a=1 gibberish b=2 c=3'; my $match2 = '^(?<a>a=(\d)).*?(?<b>b=(\d))?(?<gib>.*?)(?<c>c=(\d))$'; print qq{input1 '$input1'}; print qq{Using regex $match2}; if ($input1 =~ m/$match2/){ print qq{a '$+{a}' b '$+{b}' c '$+{c}' gib '$+{gib}'}; } else { print qq{Input1: didn't match}; } " input1 'a=1 gibberish b=2 c=3' Using regex ^(?<a>a=(\d)).*?(?<b>b=(\d))?(?<gib>.*?)(?<c>c=(\d))$ Use of uninitialized value in concatenation (.) or string at ... a 'a=1' b '' c 'c=3' gib ' gibberish b=2 '

In reply to Re: regular expression help by AnomalousMonk
in thread regular expression help by Tobin Cataldo

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.