正则表达式字符串切片

Regex String Slicing

我正在使用 Python 风格的正则表达式,我需要在替换文本时对字符串进行切片。我用来匹配所需字符串的正则表达式是 abc .+ cba。如果匹配 abc Hello, World cba,则应更改为 efg Hello, World

使用捕获组:

>>> s = "here is some stuff abc Hello, World cba here is some more stuff"
>>> import re
>>> re.sub(r'abc (.+) cba', r'efg ',s)
'here is some stuff efg Hello, World here is some more stuff'
>>>

注意:替换字符串接受反向引用。

您可以使用函数 re.sub 如下:

re.sub(pattern, repl, string, count=0, flags=0)

在repl中,支持使用\1, \2 ...反向引用组1, 2 ...中匹配的字符串,使用()。这次是 (.+)

>>> import re
>>> re.sub(r"abc (.+) cba",r"efg ", "abc Hello, World cba")
'efg Hello, World'