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

Validate email bằng regex trong Python

Validate email ID dùng regex trong Python.

Ví dụ

import re

s = 'manogna.neelam@tutorialspoint.com'
match = re.search(r'\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b', s, re.I)
print(match.group())

Kết quả

manogna.neelam@tutorialspoint.com

Giải thích pattern

  • [A-Z0-9._%+-]+: local part (chữ, số, . _ % + -)
  • @: literal @
  • [A-Z0-9.-]+: domain
  • \.[A-Z]{2,}: TLD (ít nhất 2 chữ cái)
  • re.I: case-insensitive

Lưu ý: Regex này cơ bản. Email validation hoàn chỉnh rất phức tạp (RFC 5322). Thực tế nên dùng thư viện email-validator hoặc gửi verification email.