Fom*_*aut 2 python regex python-2.7
我想在以下命令的帮助下修改字符串re.sub:
>>> re.sub("sparta", r"<b>\1</b>", "Here is Sparta.", flags=re.IGNORECASE)
Run Code Online (Sandbox Code Playgroud)
我期望得到:
'Here is <b>Sparta</b>.'
Run Code Online (Sandbox Code Playgroud)
但我得到了一个错误:
>>> re.sub("sparta", r"<b>\1</b>", "Here is Sparta.", flags=re.IGNORECASE)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/re.py", line 155, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "/usr/lib/python2.7/re.py", line 291, in filter
return sre_parse.expand_template(template, match)
File "/usr/lib/python2.7/sre_parse.py", line 833, in expand_template
raise error, "invalid group reference"
sre_constants.error: invalid group reference
Run Code Online (Sandbox Code Playgroud)
我该如何使用re.sub才能得到正确的结果?
您不在模式中指定任何捕获组,并在替换模式中使用对组 1 的反向引用。这会导致一个问题。
在模式中定义捕获组并在替换模式中使用适当的反向引用,或者使用\g<0>整个匹配的反向引用:
re.sub("sparta", r"<b>\g<0></b>", "Here is Sparta.", flags=re.IGNORECASE)
Run Code Online (Sandbox Code Playgroud)
请参阅Python 演示。