$str =~ s/(^|[^\%](?:\%\%)*)\% (\{)? # Match and capture 1 or 0 braces ([_a-zA-Z]\w*) (?(2)\}) # If there's anything in $2, match ending brace /"$1".$env->{$3}/gex; # $3 now instead of $2 here