my $str="1 2 3 10 6 7 8 11 12 13 14 15 161"; print "Before : $str\n"; # we use qr to avoid the use re 'eval'; my $rex=qr/(\d+) # match a number put it in $1 (?{$num=$1}) # set $num to be $1 (?: # dont capture all of this, \s+ # must have space between the numbers ( # capture into buffer $2 (??{'\b'.++$num.'\b'}) # match only the successor of $num ) # end of buffer )+ # one or more /x; $str=~s/$rex/$1-$2/g; # and now substitute in print "After : $str\n"; #### Before : 1 2 3 10 6 7 8 11 12 13 14 15 161 After : 1-3 10 6-8 11-15 161