python - re.sub 试图转义 repl 字符串?

标签 python regex

所以这不适用于 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/

相关文章:

python - 值错误: setting an array element with a sequence with Tensorflow

python - 如果单列有 NaN,如果 NaN 存在,如何更改整行

python - 有没有办法在谷歌应用引擎中查看内存缓存数据?

python - 在 View 中初始化表单时是否可以指定特定的表单字段?

mysql - 如何提取MySQL中某个字符之后出现的字符串?

java - 循环遍历文件并使用正则表达式查找文本

python - 为什么我会收到有关 scipy 稀疏列切片的警告?

c - 使用 sscanf 从格式化字符串中读取多个值

mysql - 用于部分包罗万象的 postfix-mysql 正则表达式

c# - NET正则表达式:{1}不起作用