如果使用正则表达式,则使用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'
>>>
注意:替换字符串接受反向引用。
关于python - 正则表达式字符串切片,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40668587/