如果是正则表达式,我使用的是 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 \1',s)
'here is some stuff efg Hello, World here is some more stuff'
>>>
注意:替换字符串接受反向引用。
