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

2024-09-27 18:24:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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

e = r"(?P<int>\d+)|(?P<alpha_num>\w)"
num = re.search(e, "123z")
letter = re.search(e, "z123")

我知道{}给出{}和{}给出{}。 同样地letter.group("int")给予Noneletter.group("alpha_num")给予z

然而,我想要的是一种为任意匹配获取“命名类别”的方法。 因此,如果我有一个任意匹配,比如new_match,我可以调用new_match.named_category(),它将根据匹配方式返回“int”或“alpha_num”

是否存在任何此类命令,或者我必须创建自己的命令

谢谢


Tags: 方法命令alpharenonenewsearchmatch
1条回答
网友
1楼 · 发布于 2024-09-27 18:24:01

对于问题中的具体示例,您可以使用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'

相关问题 更多 >

    热门问题