my $output = ""; while ($text =~ m/((.*?<\/maths>)|+|.)/gs) { if ($2) { $output .= $1; } else { my $segment = $1; $segment =~ s/+/ + /g; $output .= $segment; } } print $output . "\n";