title: perl regex replace outside of string only
body: <p>I have strings that I need to find variables inside of in order to replace them with values. Eg:</p>
  
  <pre><code>my $str = "var1 var2 blah blah blah var3"
  </code></pre>
  
  <p>Sometimes the strings have embedded strings:</p>
  
  <pre><code>my $str = "var1 var2 blah \"do not replace this: var1\" blah blah var3"
  </code></pre>
  
  <p>So I built a regex that matches strings and variables. When it matches a string, it replaces it with itself. When it matches variables, it replaces them with the results of a hash. In order to make this work in regex form, I break the captures into two parts, the named group (macro) and the last match. For strings, I capture the first quote character (") into the named group and the rest of the string into the last match. For variables, I capture the whole variable in the named group and I capture nothing in the last capture group. To handle strings, I add a hash entry for {"} = '"'. For each match, I paste the hash lookup followed by the last match. This performs admirably - although seems awkward.</p>
  
  <pre><code>$line =~ s/(?:(?&lt;macro&gt;(?&lt;!\\)")(.*?(?&lt;!\\)")|(?&lt;macro&gt;(``|\b($list_of_hash_keys)\b))())/$variables-&gt;{$+{macro}}$+/gs;
  </code></pre>
  
  <p>Is there a cleaner way in a beautiful regex form?</p>