my @temp = split /(STARTPRESERVE.*?STOPPRESERVE)/; my $output = ""; while (@temp) { local $_ = shift @temp; s/\s+/ / unless @temp % 2; $output .= $_; }