title: Escaping dollar signs in regex not working
body: <p>Before I start, I know there are better ways than regex doing this (like tokenizers), that's not what the question is about. I'm already stuck using regex, and it already works as I need to, except one special case, which is what I need advice on.</p>
  
  <p>I need to scan through some JavaScript-like code and insert the <code>new</code> keyword in front of every object declaration. I already know the names of all objects that will need this keyword, and I know that none of them will have that keyword in the code before I start (so I don't need to deal with repeated <code>new</code> words or guessing whether something is an object or not. For example, a typical line could look like this:</p>
  
  <pre><code>foo = Bar()
  </code></pre>
  
  <p>Where I would already know that <code>Bar</code> is a 'class' and would need 'new' for object declaration. The following regex does the trick:</p>
  
  <pre><code>for classname in allowed_classes:
      line = re.sub(r'^([^\'"]*(?:([\'"])[^\'"]*\2)*[^\'"]*)\b(%s\s*\()' % classname, r'\1new \3', line)
  </code></pre>
  
  <p>It works like a charm, even making sure not to touch <code>classname</code> when it's inside a string (The first portion of the regex tells it to make sure there are even number of quotes before-hand - it's a bit naive in that it will break with nested quotes, but I don't need to handle that case). Problem is, class names could also have <code>$</code> in them. So the following line is allowed as well if <code>$Bar</code> exists in allowed_classes:</p>
  
  <pre><code>foo = $Bar()
  </code></pre>
  
  <p>The above regex will ignore it, due to the dollar sign. I figured escaping it would do the trick, but this logic seems to have no effect on the above line even if <code>$Bar</code> is one of the classes:</p>
  
  <pre><code>for classname in allowed_classes:
      line = re.sub(r'^([^\'"]*(?:([\'"])[^\'"]*\2)*[^\'"]*)\b(%s\s*\()' % re.escape(classname), r'\1new \3', line)
  </code></pre>
  
  <p>I also tried escaping it by hand using <code>\</code> but it has no effect either. Can someone explain why converting <code>$</code> to <code>\$</code> isn't working and what could fix it?</p>
  
  <p>Thanks</p>