Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách trích xuất email từ văn bản bằng Python Regex

Dùng regex pattern để extract email address từ text. Lưu ý: Email validation chuẩn RFC 5322 rất phức tạp; pattern dưới đây là thực dụng (practical) cho hầu hết trường hợp.

Pattern thực dụng (Common)

import re

text = 'Contact: user@example.com, admin@test.org, invalid@.com'

# Pattern phổ biến: word chars + @ + domain với ít nhất 1 dấu chấm
pattern = r'\b[\w.+-]+@[\w-]+\.[\w.-]+\b'

emails = re.findall(pattern, text)
print(emails)
# ['user@example.com', 'admin@test.org']

Kết quả


['user@example.com', 'admin@test.org']

Pattern chặt chẽ hơn (RFC 5322 compliant - simplified)


# Local part: alphanumeric + . _ % + - (không bắt đầu/kết thúc bằng ., không .. liên tiếp)
# Domain: labels cách nhau bởi dấu chấm, mỗi label alphanumeric + hyphen (không đầu/cuối)
rfc_pattern = r'\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b'

# Test
tests = ['user@example.com', 'user.name@sub.domain.org', 'invalid@.com', 'user@domain']
for t in tests:
    print(f'{t:30} -> {bool(re.match(rfc_pattern, t))}')

Kết quả


user@example.com               -> True
user.name@sub.domain.org       -> True
invalid@.com                   -> False
user@domain                    -> False (thiếu TLD)

Extract với Named Groups


pattern = r'\b(?P[\w.+-]+)@(?P[\w-]+\.[\w.-]+)\b'

for m in re.finditer(pattern, text):
    print(f"Email: {m.group()}, Local: {m.group('local')}, Domain: {m.group('domain')}")

Lưu ý

  • Regex không validate MX record, chỉ validate format.
  • Để validate thật: gửi verification email.
  • Python 3.6+: dùng email-validator library cho validation chuẩn RFC.
  • Pattern [\w.+-]+@[\w-]+\.[\w.-]+ đủ cho 99% use case thực tế.