Địa chỉ email khá phức tạp và không có tiêu chuẩn thống nhất trên toàn cầu khiến việc nhận diện email trong regex khó khăn. RFC 5322 quy định định dạng email. Ta dùng định dạng này để trích xuất email từ văn bản.
Ví dụ, cho chuỗi đầu vào −
Hi my name is John and email address is john.doe@somecompany.co.uk and my friend's email is jane_doe124@gmail.com
Kết quả −
john.doe@somecompany.co.uk jane_doe124@gmail.com
Có thể dùng regex sau cho trích xuất −
[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+
Dùng phương thức findall từ module re. Ví dụ,
Ví dụ
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 emails: print(mail)Kết quả
Điều này sẽ cho kết quả −
john.doe@somecompany.co.uk jane_doe124@gmail.com