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

Trích xuất email từ văn bản với Regex trong Python

Sử dụng module re (regular expression) để tìm tất cả địa chỉ email trong chuỗi văn bản.

Pattern email cơ bản

r"[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+"

Ví dụ

import re

my_text = ("Please contact us at contact@tutorialspoint.com for further information. "
           "You can also give feedback at feedback@tutorialspoint.com")

my_emails = re.findall(r"[a-z0-9\.\-+_]+@[a-z0-9\.\-+_]+\.[a-z]+", my_text)
print(my_emails)
# Output: ['contact@tutorialspoint.com', 'feedback@tutorialspoint.com']

Giải thích pattern

  • [a-z0-9\.\-+_]+: phần local (trước @), cho phép chữ, số, dấu chấm, gạch ngang, plus, underscore.
  • @: ký tự @ bắt buộc.
  • [a-z0-9\.\-+_]+: tên miền.
  • \.[a-z]+: phần mở rộng (.com, .org, .vn...).

Pattern mạnh mẽ hơn (RFC 5322)

import re
email_regex = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
# Hỗ trợ chữ hoa, domain nhiều cấp, TLD 2+ ký tự

Ứng dụng

  • Thu thập email từ file log, trang web, tài liệu.
  • Validate form nhập liệu.
  • Phân tích dữ liệu khách hàng.