所以这不适用于 python 的正则表达式:
>>> re.sub('oof', 'bar\\', 'foooof')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\re.py", line 151, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "C:\Python27\lib\re.py", line 270, in _subx
template = _compile_repl(template, pattern)
File "C:\Python27\lib\re.py", line 257, in _compile_repl
raise error, v # invalid expression
error: bogus escape (end of line)
我以为我的眼睛在欺骗我,所以我这样做了:
>>> re.sub('oof', "bar\x5c", 'foooof')
得到了同样的东西。我已经搜索并确认人们有这个问题。那么将 repl 当作一个普通的字符串会有什么问题呢?是否可以在 repl 中放置其他格式设置选项?
最佳答案
如果不想处理字符串转义,可以使用lambda,不处理字符串:
>>> re.sub('oof', lambda x: 'bar\\', 'foooof')
'foobar\\'
>>> s=re.sub('oof', lambda x: 'bar\\', 'foooof')
>>> print s
foobar\
但打印时仍会被解释:
>>> re.sub('oof', lambda x: 'bar\r\\', 'foooof')
'foobar\r\\'
>>> print re.sub('oof', lambda x: 'bar\r\\', 'foooof')
\oobar
或者,使用原始字符串:
>>> re.sub('oof', r'bar\\', 'foooof')
'foobar\\'
关于python - re.sub 试图转义 repl 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16291396/