chomp( (undef, $_, undef, @words) = <> ); %restore_case = map { lc, $_ } @words; $list = join '|', map { scalar reverse lc } @words; m/^ (?: ($list | $ | (?{ pop @submatches }) (?!) ) (?{ push @submatches, $^N }) )+ $/x; pop @submatches; print join ' ', map { $restore_case{ scalar reverse } } @submatches #### m/^ (?: ( $list # dictionary joined with '|' | $ # if end of line then success, so don't pop array | (?{ pop @submatches }) (?!) # pop array and suddenly fail ) (?{ push @submatches, $^N }) # after every matched word, push it to array # $^N - last captured group )+ $/x; #### ":aa2bb4cc6dd8" =~ / (:) (?{ [] }) # initialize $^R (?: (\w\w) (\d) # add captures to $^R: (?{ [@{$^R}, [$2, $3]] }) )* /x; #### my @R; ":aa2bb4cc6dd8" =~ / (:) (?: (\w\w) (\d) (?{ push @R, [$2, $3] }) )* /x; #### use Data::Dumper; sub dd { print Dumper(shift) }; ("aa2bb4cc6dd8" x 1e3) =~ / (?{ [] }) # initialize $^R (?: (\w\w) (\d) # add captures to $^R: (?{ [@{$^R}, [$1, $2]] }) )* /x; dd @{ $^R }[ -1 ] #### use Data::Dumper; sub dd { print Dumper(shift) }; my @R = (); ("aa2bb4cc6dd8" x 5e3) =~ / (?: (\w\w) (\d) # push captures to @R: (?{ push @R, [$1, $2] }) )* /x; dd @R[ -1 ] #### $VAR1 = [ 'dd', '8' ];