Python正则表达式实现字符串unescaping

epl*_*ess 13 python regex backreference

我试图用Python正则表达式和反向引用实现字符串unescaping,它似乎不想工作得很好.我确定这是我做错了但我无法弄清楚是什么......

>>> import re
>>> mystring = r"This is \n a test \r"
>>> p = re.compile( "\\\\(\\S)" )
>>> p.sub( "\\1", mystring )
'This is n a test r'
>>> p.sub( "\\\\\\1", mystring )
'This is \\n a test \\r'
>>> p.sub( "\\\\1", mystring )
'This is \\1 a test \\1'
Run Code Online (Sandbox Code Playgroud)

我想用\ [char]替换\\ [char],但是Python中的反向引用似乎没有遵循他们在我曾经使用的每个其他实现中执行的相同规则.有人能解开一些光吗?

mar*_*asc 8

这不是安德斯的第二个例子吗?

在2.5中,string-escape您还可以应用以下编码:

>>> mystring = r"This is \n a test \r"
>>> mystring.decode('string-escape')
'This is \n a test \r'
>>> print mystring.decode('string-escape')
This is 
 a test 
>>> 
Run Code Online (Sandbox Code Playgroud)