Skip to main content
 首页 » 编程设计

python之提取正则表达式的一部分 (Python)

2025年01月19日35freeliver54

假设我有以下正则表达式和搜索

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'