我正在尝试使用 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 中的反向引用似乎并不遵循我曾经使用过的所有其他实现中的相同规则。有人可以透露一些信息吗?

有帮助吗?

解决方案

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

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

其他提示

好吧,我想你可能错过了 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 \
>>>

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

我的想法是,我将读入转义字符串,然后取消转义(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

你被 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

标记;他的第二个示例要求首先将每个转义字符放入数组中,如果转义序列碰巧不在数组中,则会生成 KeyError。除了提供的三个字符之外,它都会死掉(尝试 \v ),并且每次想要对字符串进行转义(或保留全局数组)时枚举每个可能的转义序列是一个非常糟糕的解决方案。与 PHP 类似,使用 preg_replace_callback() 用 lambda 代替 preg_replace(), ,在这种情况下这是完全没有必要的。

如果我在这件事上表现得像个混蛋,我很抱歉,我只是对 Python 感到非常沮丧。我曾经使用过的所有其他正则表达式引擎都支持这一点,但我不明白为什么这不起作用。

感谢您的回复;这 string.decode('string-escape') 功能正是我最初想要的。如果有人对正则表达式反向引用问题有通用的解决方案,请随意发布,我也会接受它作为答案。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top