my $str = <<'EOS'; abc "a\"bc$xyz$abc$x$y" $bla'h, $blah hello k\$nob this is "\"'abc$xy$z\"" test "$" a$$bc "$$abc$xyz$abc$" blah, $$, blah abc "a\"bc$xy\\z$abc$x$y\\" $bla'h, "$baz" EOS print "$str\n\n"; $str =~ s[ \G # Don't skip anything ( # $1 is unquoted text (?: [^\\"]+ # Uninteresting stuff | \\. # Escaped character )* )( # $2 is quoted text " # Opening quote (?: [^\\"]+ # Unintersting stuff | \\. # Escaped character )* ("?) # $3 is closing quote ) ][ die "Unclosed quote ($2)" unless $3; my $t = $1; # changed line my $q = $2; $q =~ s[\$][\\\$]g; $t . $q; # changed line ]xseg; print $str;