Python正则表达式实现字符串反转义

17

我正在尝试使用Python正则表达式和反向引用来实现字符串反转义,但似乎它并不起作用。我确信是我做错了什么,但我无法弄清楚问题所在...

>>> 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'

我想用\[char]替换\\[char],但是在Python中回溯引用似乎不遵循我曾经使用的其他实现的相同规则。能否有人解释一下?

5个回答

10

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

在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 
>>> 

3

嗯,我认为您可能错过了r或者数了错误的反斜杠...

"\\n" == r"\n"

>>> import re
>>> mystring = r"This is \\n a test \\r"
>>> p = re.compile( r"[\\][\\](.)" )
>>> print p.sub( r"\\\1", mystring )
This is \n a test \r
>>>

如果我理解正确,您需要的是这个。

我猜更常见的请求是这个:

>>> d = {'n':'\n', 'r':'\r', 'f':'\f'}
>>> p = re.compile(r"[\\]([nrfv])")
>>> print p.sub(lambda mo: d[mo.group(1)], mystring)
This is \
 a test \
>>>

有兴趣的学生还应该阅读肯·汤普森的《关于信任的反思》,在其中,我们的英雄使用类似的例子来解释不要相信你没有从机器代码自己引导编译器的危险。


1

我的想法是读入一个转义字符串,并对其进行反转义(这是Python明显缺少的功能,你不应该首先使用正则表达式来解决这个问题)。不幸的是,我被反斜杠所困扰...

另一个说明性的例子:

>>> mystring = r"This is \n ridiculous"
>>> print mystring
This is \n ridiculous
>>> p = re.compile( r"\\(\S)" )
>>> print p.sub( 'bloody', mystring )
This is bloody ridiculous
>>> print p.sub( r'\1', mystring )
This is n ridiculous
>>> print p.sub( r'\\1', mystring )
This is \1 ridiculous
>>> print p.sub( r'\\\1', mystring )
This is \n ridiculous

我希望它打印的是:
This is 
ridiculous

0

你被 Python 对结果字符串的表示所欺骗了。Python 表达式:

'This is \\n a test \\r'

代表字符串

This is \n a test \r

这应该是你想要的。尝试在每个p.sub()调用前添加'print',以打印实际返回的字符串,而不是Python字符串表示。

>>> mystring = r"This is \n a test \r"
>>> mystring
'This is \\n a test \\r'
>>> print mystring
This is \n a test \r

0

Mark;他的第二个例子需要将每个转义字符最初放入一个数组中,如果逃逸序列恰好不在该数组中,则会生成KeyError。它只能用于提供的三个字符以外的情况(试试\v),每次想要取消字符串转义时都枚举所有可能的转义序列(或保持全局数组)都是一个非常糟糕的解决方案。类似于PHP,这就像在这种情况下使用带有lambda的preg_replace_callback()而不是preg_replace()一样,完全没有必要。

如果我对此感到不满,请不要介意,我只是对Python感到非常沮丧。这是我使用过的其他任何正则表达式引擎都支持的事实,我无法理解为什么这不能起作用。

谢谢您的回复;string.decode('string-escape')函数正是我最初寻找的内容。如果有人对正则表达式反向引用问题有通用解决方案,请随时发帖,我会接受那个答案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接