my $re = join("([wxyz]*)", "", split("", $A), ""); if (my @array = $B =~ /^$re$/) { print "$_\n" for grep length, @array; }