$phrase = '$foo $(bar)'; $variables = { foo => '$(bar)', bar => '$(foo)' }; $phrase =~ s/ (?: # Just take the first one \$([a-zA-Z0-9_]+) ) | # And alternate it with the second (?: \$\(([a-zA-Z0-9_]+)\) ) /$variables->{$1||$2}/xg; # Then do the substitution for the one # that matched print $phrase; # Prints "$(bar) $(foo)"