gpt4 book ai didi

python - 在 python 中命名为非捕获组?

转载 作者:行者123 更新时间:2023-12-04 22:47:54 29 4
gpt4 key购买 nike

是否可以在 python 中命名非捕获组?例如,我想匹配此模式中的字符串(包括引号):

“a=b”
'鸟=天使'

我可以执行以下操作:

s = '"bird=angel"'
myre = re.compile(r'(?P<quote>[\'"])(\w+)=(\w+)(?P=quote)')
m = myre.search(s)
m.groups()
# ('"', 'bird', 'angel')

结果捕获了报价组,这在此处是不可取的。

最佳答案

不,命名组总是捕获组。来自 re 的文档模块:

Extensions usually do not create a new group; (?P<name>...) is the only exception to this rule.



关于命名组扩展:

Similar to regular parentheses, but the substring matched by the group is accessible within the rest of the regular expression via the symbolic group name name



在哪里 regular parentheses表示 (...) ,与 (?:...) 相比.

关于python - 在 python 中命名为非捕获组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16471776/

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