title: How to ignore some delimited text when doing Python re.sub
body: <p>I'm trying to &quot;parse&quot; some LaTeX code. LaTeX uses some special characters such as <code>%</code>, <code>#</code>, <code>{</code>, <code>}</code> and delimits inline math environments with <code>$ … $</code>.</p>
  <p>What I need is to escape (<code>\</code>) all special chars that are not already escaped and <em>are not</em> inside <code>$ … $</code>.</p>
  <p>For example, for the provided entry</p>
  <pre><code>#s{o}me\%thing $ \text{a} $
  </code></pre>
  <p>I need to return:</p>
  <pre><code>\#s\{o\}me\%thing $ \text{a} $
  </code></pre>
  <p>Note that the already escaped <code>\%</code>, as well as the <code>\text{a}</code> within <code>$ … $</code>, remain untouched.</p>
  <p>I'm using Python's <code>re.sub</code> to do that, and this way I can ignore the escaped ones, but I don't know how to ignore <code>$ … $</code> environments. My current code is:</p>
  <pre class="lang-py prettyprint-override"><code>string = &quot;#s{o}me\%thing $ \text{a} $&quot;
  re.sub(r'([^\\]?)((?:%|#|{|}|&amp;))', r&quot;\1\\\2&quot;, string)
  # Expected output: &quot;\#s\{o\}me\%thing $ \text{a} $&quot;
  # Actual output:   &quot;\#s\{o\}me\%thing $ \text\{a\} $&quot;
  </code></pre>
  <p>At this time, my code returns, for the example above, the following:</p>
  <pre><code>\#s\{o\}me\%thing $ \text\{a\} $
  </code></pre>
  <p>Any suggestions??</p>