我想弄清楚如何改进正则表达式以仅获取不以 ".jpg" 结尾的 emails 并删除 -- 从电子邮件的左右部分(如果找到的话)。示例参数为 source,它是一个字符串。
<html>
<body>
<p>aaa@example.jpg</p>
<p>--bbb@example.com--</p>
<p>ccc@example.com--</p>
<p>--ddd@example.com</p>
</body>
</html>
结果应包含:bbb@example.com, ccc@example.com, ddd@example.com 所以基本上,我无论如何都想改进这个功能,这样正则表达式就可以生成电子邮件而无需——如果可能的话,改进 if not email[0].endswith('.png') 以防万一我想添加更多,这看起来很丑陋。
def extract_emails(source):
regex = re.compile(r'([\w\-\.]{1,100}@(\w[\w\-]+\.)+[\w\-]+)')
emails = list(set(regex.findall(source.decode("utf8"))))
all_emails = []
for email in emails:
if not email[0].endswith('.png') and not email[0].endswith('.jpg') \
and not email[0].endswith('.gif') and not email[0].endswith('.rar')\
and not email[0].endswith('.zip') and not email[0].endswith('.swf'):
all_emails.append(email[0].lower())
return list(set(all_emails))
请您参考如下方法:
我认为顶级域很少,所以您可以使用alternation
s="""<html>
<body>
<p>aaa@example.jpg</p>
<p>--bbb@example.com--</p>
<p>ccc@example.com--</p>
<p>--ddd@example.com</p>
</body>
</html>"""
print re.findall(r"-*([\w\.]{1,100}@\w[\w\-]+\.+com|biz|us|bd)-*",s)
['bbb@example.com', 'ccc@example.com', 'ddd@example.com']
参见 DEMO
或尝试 \w+@\w+\.(?!jpg|png)\w+\.*\w*
s="""<html>
<body>
<p>aaa@example.jpg</p>
<p>--bbb@example.com--</p>
<p>ccc@example.com--</p>
<p>--ddd@example.com</p>
</body>
</html>"""
print re.findall(r"\w+@\w+\.(?!jpg|png)\w+\.*\w*",s)
很难为电子邮件验证设置常量正则表达式- 电子邮件验证的详细信息请访问 Using a regular expression to validate an email address它有 69 个答案。
