s/(\d+) # first number (group #1) (?: # group #2 , # followed by a comma ( # group #3 (??{$++1}) # match previous number + 1 (group 4) ) # end group #3 )+ # end group #4, repeat /$1-$+/gx; # substitute for the first number followed by the # last matched one