Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

แยกที่อยู่อีเมลด้วย Regular Expressions ใน Python

ที่อยู่อีเมลซับซ้อน ไม่มีมาตรฐานเดียวทั่วโลก ทำให้ยากที่จะระบุใน regex 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

ใช้ regex นี้สำหรับแยก

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

ใช้ findall จาก re module

ตัวอย่าง

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)

ผลลัพธ์

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