假设我有以下正则表达式和搜索
e = r"(?P<int>\d+)|(?P<alpha_num>\w)"
num = re.search(e, "123z")
letter = re.search(e, "z123")
我知道 num.group("int")
给出 123
而 num.group("alpha_num")
给出 无
。
类似地,letter.group("int")
给出 None
和 letter.group("alpha_num")
给出 z
但是,我想要的是一种为任意匹配获取“命名类别”的方法。
因此,如果我有任意匹配项,比如 new_match,我可以调用 new_match.named_category()
,它会根据匹配方式返回“int”或“alpha_num”。
是否存在任何此类命令,还是我必须创建自己的命令?
谢谢!
最佳答案
对于您问题中的具体示例,您可以使用 lastgroup :
>>> import re
>>> e = r"(?P<int>\d+)|(?P<alpha_num>\w)"
>>> num = re.search(e, "123z")
>>> letter = re.search(e, "z123")
>>> num.lastgroup
'int'
>>> letter.lastgroup
'alpha_num'
关于python - 提取正则表达式的一部分 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49215525/