$number_set = "6 7 8 9 10"; #### $number_set = "6 7 8 9 10"; $number_set =~ s/ (?>(\d+)) # prevent backtracking, so that # a failed match after a '10' # won't try 1 and 0 individually (?{local $first = $1}) # set $first eq to the number # just matched ( \s # match a space ((??{++$first})) # followed by the number after # the one just matched )+ # as many times as possible, # but at least once /$1-$+/gx; # and replace it with the original $1, # a dash, and the last number matched