gpt4 book ai didi

python - 正则表达式字符串切片

转载 作者:太空宇宙 更新时间:2023-11-04 08:45:52 24 4
gpt4 key购买 nike

如果是正则表达式,我使用的是 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com