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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |