[英]Python regex to remove capture email between dashes or ignore emails ending with .jpg etc
我试图弄清楚如何改进正则表达式,使其仅接收不以".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因此,基本上,我想无论如何都希望改进此功能,以便regex可以生成不带电子邮件的电子邮件-如果可能,可以改善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']
见演示
或尝试\\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)
为电子邮件验证设置常量正则表达式非常困难-有关电子邮件验证的详细信息,请参见使用正则表达式来验证具有69个答案的电子邮件地址 。
x="""<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\-]+\.)+(?!jpg)[\w]+)-*",x)
输出: ['bbb@example.com', 'ccc@example.com', 'ddd@example.com']
最好的方法是使用HTML解析器,例如BeautifulSoup
In [37]: from bs4 import BeautifulSoup
In [38]: soup = BeautifulSoup('''<html>
....: <body>
....: <p>aaa@example.jpg</p>
....: <p>--bbb@example.com--</p>
....: <p>ccc@example.com--</p>
....: <p>--ddd@example.com</p>
....:
....: </body>
....: </html>''', 'lxml')
In [39]: [email.strip('-') for email in soup.stripped_strings if not email.endswith('.jpg')]
Out[39]: ['bbb@example.com', 'ccc@example.com', 'ddd@example.com']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.