是否可以在 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/