#!C:/strawberry/perl/bin/perl.exe # use strict; use warnings; my $string = "aacbbbcac"; my $re1 = qr/((a+)?(b+)?(c))*/; #my $re1 = qr/((a*)(b*)(c))*/; #my $re1 = qr/((a+)?(b*)(c))*/; if ($string =~ $re1) { my $start = 0; my @something; foreach (0..$#-) { if(defined($-[$_])) { $start = $-[$_] if($-[$_] > $start); if($-[$_] >= $start) { printf "Group %d: <%s>\n", $_, substr($string, $-[$_], $+[$_] - $-[$_]); $something[$_] = substr($string, $-[$_], $+[$_] - $-[$_]); } else { printf "Group %d: <%s> - but ignore it because it is from a previous iteration of the outer capture group\n", $_, substr($string, $-[$_], $+[$_] - $-[$_]); $something[$_] = ''; } } else { printf "Group %d: hasn't matched yet\n", $_; $something[$_] = ''; } } print "$1 = " . join('', @something[2..4]) . "\n"; }