my $param = 'password'; for ( q~{'password' => 'secret'}~, q~{"password" => "sec\"ret"}~ ) { $_ =~ s/ ( # capture everything up to the start of the value ( # capture the quotation mark we are using (? | : ) # perl or JSON key-value "connector" \s* # any amount of space \2 # the same quotation mark ) # end capture everything up to start of the value (?: # group but do not capture the value (?!\2) . # defined as any character except the same quote )* # any number of times /$1***/smxg; # the closing quotation mark will remain in place say $_; }