my $str = "25 {fred and barney} text 2.36 12.0 {bam bam} text {pebbles}"; print "before - $str\n"; substr($str, pos($str) - length($1), length $1) =~ s/ /_/g while $str =~ /\G .*? { ( [^}]+ ) } /xg; print "after - $str\n"; __output__ before - 25 {fred and barney} text 2.36 12.0 {bam bam} text {pebbles} after - 25 {fred_and_barney} text 2.36 12.0 {bam_bam} text {pebbles}