#! perl use strict; use warnings; my $string = ' 2 0 1 2 - 7 - 2 7 9 : 3 7 : 3 1 '; # NB: 2 spaces here ^^ # (a) Remove single spaces 1 while $string =~ s/(^|[^ ])[ ]([^ ]|$)/$1$2/g; # (b) Squash multiple spaces down to one $string =~ s/[ ]{2,}/ /g; print "'", $string, "'\n";