my $foo = "x.....xxx.x.....x......xxx...xx...x...xxx"; my @array = $foo =~ /( # capture in $1 [x] # match an opening x (?:[^x]*?[x][^x]*?) # match an x surrounded by some non-x {2} # match n-2 times [x] # match a closing x )/gx; #(?{push @array, $1}) # keep the match #$ # match the end of the string to force back-tracking print "$_\n" foreach (sort {length $a <=> length $b} @array); __END__ x.....xxx x...xx...x x.....x......xx