Python Regular Expressions to implement string unescaping
<p>I'm trying to implement string unescaping with Python regex and backreferences, and it doesn't seem to want to work very well. I'm sure it's something I'm doing wrong but I can't figure out what...</p>

<pre><code>&gt;&gt;&gt; import re
&gt;&gt;&gt; mystring = r"This is \n a test \r"
&gt;&gt;&gt; p = re.compile( "\\\\(\\S)" )
&gt;&gt;&gt; p.sub( "\\1", mystring )
'This is n a test r'
&gt;&gt;&gt; p.sub( "\\\\\\1", mystring )
'This is \\n a test \\r'
&gt;&gt;&gt; p.sub( "\\\\1", mystring )
'This is \\1 a test \\1'
</code></pre>

<p>I'd like to replace \\[char] with \[char], but backreferences in Python don't appear to follow the same rules they do in every other implementation I've ever used. Could someone shed some light?</p>

<p>Isn't that what <a href="#13844">Anders' second example</a> does?</p>

<p>In 2.5 there's also a <code>string-escape</code> encoding you can apply:</p>

<pre><code>&gt;&gt;&gt; mystring = r"This is \n a test \r"
&gt;&gt;&gt; mystring.decode('string-escape')
'This is \n a test \r'
&gt;&gt;&gt; print mystring.decode('string-escape')
This is 
 a test 
&gt;&gt;&gt;
</code></pre>
