in reply to substitute instead global matching for nested matches

Think lines and grab just those you want. Consider:

use strict; use warnings; my $fc = <<FC; #4 r0 ! r1 ! r2 ! #5 r3 ! r4 ! r5 ! FC print "$1\n$2\n" while $fc =~ /^(#\d+).*?^.*?^(.*?)$/gms;

Prints:

#4 r0 ! #5 r3 !

Note the regex switches - g to match multiple times, s to let . match new line characters, and m to perform a multi-line match which allows the internal ^ and $ matches to work.

True laziness is hard work

Replies are listed 'Best First'.
Re^2: substitute instead global matching for nested matches
by utku (Acolyte) on Mar 18, 2012 at 23:06 UTC

    This returns the first element in the 2nd match. I need to get the last element. So the result must be

    #4 r2 ! #5 r5 !

    And your code is restricted to 3 consecutive elements separated by lines. I need to a more generic solution because my lists are changing variably. Sorry did not mention that clearly in my previous post (the global match ((\S+\s+\S+\s+)*) implies that). So a $fc could be

    #4 r1 ! #5 r3 ! r7 ! r10 ! #8 r0 ! r1 !

    I need to get the last r member. Any help appreciated.

      The following meets your current spec as I understand it:

      use strict; use warnings; my $fc = <<FC; #4 r2 ! #5 r3 ! r7 ! r10 ! #8 r0 ! r1 ! FC print "$1\n$2\n" while $fc =~ /^(#\d+)[^#]*^([^#\n]+)$/gm;

      Prints:

      #4 r2 ! #5 r10 ! #8 r1 !
      True laziness is hard work
        It works! GrandFather, thanks for the tip about pattern matching!