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 #### 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 ) (?{push @array, $1}) # keep the match $ # match the end of the string to force back-tracking /x; print "$_\n" foreach (sort {length $a <=> length $b} @array); __END__ xxx.x xxx...x xx...xx xx...xx xx...xx xx...xx x...xxx x.....xxx xx.x.....x xx.x.....x x......xxx x...xx...x xx...x...x xx...x...x xx...x...x xx...x...x x...x...xx x...x...xx x...x...xx x...x...xx x.....x......xx x.....x......xx x.....x......xx x.....x......xx x.....x......xx x.....x......xx x.....x......xx x.x.....x......x x.x.....x......x x.x.....x......x x.x.....x......x x.x.....x......x x.x.....x......x