带有正则表达式的Python 3.7:为什么我不能再用包含反斜杠(\)的字符串替换?

问题描述 投票:2回答:1

对于我的问题,我有一个非常简单的示例:

import re
my_string = re.sub(r"Hello", r"\Greetings", "Hello Folks!")
print(my_string)

以上内容在Python 3.6中将\Greetings Folks!打印到标准输出。让我们在Python 3.7.0或3.7.4(我能够测试的版本)中再试一次。怎么了?我们收到一个错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.7/re.py", line 192, in sub
    return _compile(pattern, flags).sub(repl, string, count)
  File "/usr/lib/python3.7/re.py", line 309, in _subx
    template = _compile_repl(template, pattern)
  File "/usr/lib/python3.7/re.py", line 300, in _compile_repl
    return sre_parse.parse_template(repl, pattern)
  File "/usr/lib/python3.7/sre_parse.py", line 1024, in parse_template
    raise s.error('bad escape %s' % this, len(this))
re.error: bad escape \G at position 0

为什么?我错过了Python 3.7中的变化吗?解决此问题的正确方法是什么?

python regex python-3.x python-3.7
1个回答
1
投票

我想您正在使用\G构造,如果您已经安装了regex模块,则可以使用该构造。可以删除该行或添加另一个反斜杠。

import re
my_string = re.sub(r"Hello", r"\\Greetings", "Hello Folks!")
print(my_string)

替代:

$pip install regex

$pip3 install regex

然后,

import regex
my_string = regex.sub(r"Hello", r"\Greetings", "Hello Folks!")
print(my_string)

输出

\Greetings Folks!
© www.soinside.com 2019 - 2024. All rights reserved.