在python中获取正则表达式以返回匹配的模式(不是匹配对象)

Jor*_*les 1 python regex

所以我在几个字符串行中的其他内容中有一个电子邮件列表。我希望我的代码仅返回匹配的模式,函数如下:

def match_separator(s):
    mail = s.lower()
    mail = re.match(r"[^@]+@[a-z0-9]+(\.[a-z0-9]+){1,2}",s)
    print(mail)
Run Code Online (Sandbox Code Playgroud)

看起来它正确地找到了电子邮件,但它返回的结果对我的后续步骤毫无用处:

def match_separator(s):
    mail = s.lower()
    mail = re.match(r"[^@]+@[a-z0-9]+(\.[a-z0-9]+){1,2}",s)
    print(mail)
Run Code Online (Sandbox Code Playgroud)

我无法用这个输出做任何事情。我根据我从类似文档中理解的内容尝试了几件事print(mail.group(0)),但唯一让我感兴趣的是:

AttributeError: 'NoneType' object has no attribute 'group'
Run Code Online (Sandbox Code Playgroud)

关于如何做到这一点有什么想法吗?看起来在正则表达式中获取匹配的模式应该非常简单(这是大多数用例所追求的,对吧?)但我在这里。

编辑 好的,谢谢大家,我很迟钝,这就是原因:

传递给函数的第一行没有匹配项,因此程序以异常结束。此更改解决了我的问题:

def match_separator(s):
    mail = s.lower()
    mail = re.match(r"[^@]+@[a-z0-9]+(\.[a-z0-9]+){1,2}",s)
    try:
        print(mail.group())
    except AttributeError:
        pass
Run Code Online (Sandbox Code Playgroud)

这会绕过不匹配的第一行,只返回我想要的内容。

Cor*_*mer 5

您确实可以使用该group方法来提取匹配项

>>> import re
>>> m = re.match(r"[^@]+@[a-z0-9]+(\.[a-z0-9]+){1,2}", 'xx@gmail.com')
>>> m
<re.Match object; span=(0, 12), match='xx@gmail.com'>
>>> m.group(0)
'xx@gmail.com'
Run Code Online (Sandbox Code Playgroud)

如果您遇到该错误,则意味着您传递到函数中的任何字符串都没有匹配项,因此没有匹配项,m并且None没有任何内容可显示。

>>> m = re.match(r"[^@]+@[a-z0-9]+(\.[a-z0-9]+){1,2}", 'bad_input')
>>> m
>>> type(m)
<class 'NoneType'>
Run Code Online (Sandbox Code Playgroud)