gpt4 book ai didi

python - re.sub 仅适用于捕获组

转载 作者:行者123 更新时间:2023-12-01 23:16:15 26 4
gpt4 key购买 nike

给定字符串:

s = '<Operation dedupeMode="normal" name="update">'

我想将重复数据删除模式更改为手动。例如,最终结果应该是:

s = '<Operation dedupeMode="manual" name="update">'

是否有办法使用 re.sub 只替换捕获的组而不替换其他内容?这是我到目前为止所拥有的,但它取代了所有内容,而不仅仅是捕获的组:

import re
s = '''<Operation dedupMode="normal" name="update">'''
re.sub(r'dedupMode="(normal|accept|manual|review)"', "manual", s)
# '<Operation manual name="update">'

最佳答案

您可以切换捕获组来捕获 dedupMode="和结尾的 "

(dedupMode=")(?:normal|accept|manual|review)(")

并替换为

\1manual\2

Regex demo | Python demo

或者也许使用环视

(?<=dedupMode=")(?:normal|accept|manual|review)(?=")

并替换为

manual

Regex demo | Python demo

对于选项,您可以使用非捕获组(?:

请注意manual 也存在于替换中,可能会被省略,因为它与替换值相同。

关于python - re.sub 仅适用于捕获组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59256253/

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