使用 Python 中的正則表示式提取電子郵件地址


電子郵件地址非常複雜,而且沒有適用於全球的標準,這使得在正則表示式中識別電子郵件變得困難。RFC 5322 指定了電子郵件地址的格式。我們將使用此格式從文字中提取電子郵件地址。

例如,對於給定的輸入字串 -

Hi my name is John and email address is john.doe@somecompany.co.uk and my friend's email is jane_doe124@gmail.com

我們應該得到以下輸出 -

john.doe@somecompany.co.uk
jane_doe124@gmail.com

我們可以使用以下正則表示式進行提取 -

[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+

我們可以使用 re 模組中的查詢全部方法來提取電子郵件地址。例如,

示例

import re

my_str = "Hi my name is John and email address is john.doe@somecompany.co.uk and my friend's email is jane_doe124@gmail.com"
emails = re.findall("([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)", my_str)

for mail in an email:
print(mail)

輸出

將給出以下輸出 -

john.doe@somecompany.co.uk
jane_doe124@gmail.com

更新於:2020 年 6 月 20 日

5000+ 次瀏覽

啟動你的事業

完成課程並獲得認證

開始
廣告
© . All rights reserved.