title: regex search&replace a variable string including a regex statement
body: <p>I want to use <code>re.sub</code> to replace a part of a string I know exactly what looks like. relevant part of code:</p>
  
  <pre><code>print "Regex statement: ", foundStatements[iterator]
  print "string to replace with : \n", latexPreparedString
  print "string to search&amp;replace in: \n", fileAsString
  processedString = re.sub(foundStatements[iterator], latexPreparedString, fileAsString)
  print "processed string: \n", processedString
  </code></pre>
  
  <p>In my testing case, <code>foundStatements[iterator]</code> is <code>"%@import script_example.py ( *out =(.|\n)*?return out)"</code> But even though <code>processedString</code> contains <code>foundStatements[iterator]</code>, <code>processedString</code> looks exactly like <code>fileAsString</code>, so it hasn't accomplished the <code>re.sub</code> task. What am I doing wrong?</p>
  
  <p><strong>EDIT</strong>: Ok, it definitely has something to do with the string I'm searching to replace containing regex code. Is there a way to make it just interpret it <code>foundStatements[iterator]</code> as a raw string to search for? The only solution I can think of is to create a function that replaces any regex symbols in a string with \regexsymbol (e.g. * -> \*), but it'd make sense for there to be a way to solve this with inbuilt functions. It'd also be a bit overkill since I'd have to make sure it works with every single regex symbol, of which there are quite a few :/</p>
  
  <p><strong>EDIT2</strong>: Well, just changing it to <code>re.sub(re.escape(foundStatements[iterator]), latexPreparedString, fileAsString)</code> seems to work. except when the regex statement doesn't hit anything in the original file. To explain, <code>latexPreparedString</code> is generated by using the regex-part of the <code>foundStatements[iterator]</code>. While it's logical that it shouldn't be able to set <code>latexPreparedString</code> to anything when the regex statement doesn't hit anything, I set <code>latexPreparedString = "</code>" by default, so in that case it should <code>re.sub</code> replace it with a blank string if it doesn't hit anything. Here's how to code looks at the moment: <a href="http://pastebin.com/wUedK3LN" rel="nofollow">pastebin.com/wUedK3LN</a></p>