in reply to Question on Regex grouping

I'm looking to capture the value of the 8 digit number found in the second regex
foreach $arr ("foo abc12345 def12345678 bar") { if (($arr =~ /(\w*)(abc)(\d{5})/) && ($arr =~ / (\w*)(def)(\d{8})/ +)) { print $3; # "12345678" } }

Replies are listed 'Best First'.
Re^2: Question on Regex grouping
by ajguitarmaniac (Sexton) on Dec 21, 2010 at 06:36 UTC

    Thanks Anonyrnous Monk! Does this mean that, irrespective of the number of regexes I write within the IF statement, $3 would point to the 3rd group of the last regex? Out of curiosity,what do I have to do if I need to print the 5 digit number in the first regex as well? Please bear with my questions if at all they sound silly. I'm new to perl and I really want to learn! Thanks :-)

      http://search.cpan.org/~jesse/perl-5.12.2/pod/perlre.pod#Capture_buffers
      The numbered match variables ($1, $2, $3, etc.) and the related punctuation set ($+, $&, $`, $', and $^N) are all dynamically scoped until the end of the enclosing block or until the next successful match

      Out of curiosity,what do I have to do if I need to print the 5 digit number in the first regex as well?

      store it, or print it before performing another match operation

      Numbering of captures counts per match/regex, of which you have two here - the one with the 8-digit capture being evaluated last.

      If you wanted to extract the 5-digit number from the first regex, you could simply reverse the order of the &&-combined tests:

      if (($arr =~ / (\w*)(def)(\d{8})/) && ($arr =~ /(\w*)(abc)(\d{5})/)) {

      Now, $3 is the 5-digit number.

      If you wanted to keep all captures, you could assign them to variables, e.g.:

      if (( my ($c1, $c2, $c3) = $arr =~ /(\w*)(abc)(\d{5})/) && ( my ($c4, $c5, $c6) = $arr =~ / (\w*)(def)(\d{8})/)) {

        Great! Just what I was looking for! Can I use the below mentioned approach to arrive at the same result?

        if ($arr =~ /(\w*)(abc)(\d{5})/){ $a = $3 if (($arr =~ / (\w*)(def)(\d{8})/){ $b = $3 } } print $a; prnit $b;