$_ = "your long string"; my $output = ""; while (/\G(.*?)(STARTPRESERVE.*?STOPPRESERVE)/gcs) { my ($left, $right) = ($1, $2); # I wish I could shortcut that above :( $left =~ s/\s+/ /g; $output .= "$left$right"; } # last bit: if (/\G(.+)/gcs) { my ($left) = $1; $left =~ s/\s+/ /g; $output .= $left; }