是否有一个好方法来检查表单输入使用正则表达式,以确保它是一个正确的风格的电子邮件地址?从昨晚开始搜索,每个人都回答了关于这个话题的问题,如果它是一个子域名的电子邮件地址,似乎也有问题。


当前回答

电子邮件地址并不像看上去那么简单!例如,Bob_O'Reilly+tag@example.com是一个有效的电子邮件地址。

我在lepl包(http://www.acooke.org/lepl/)上有一些运气。它可以验证RFC 3696中指出的电子邮件地址:http://www.faqs.org/rfcs/rfc3696.html

找到一些旧代码:

import lepl.apps.rfc3696
email_validator = lepl.apps.rfc3696.Email()
if not email_validator("email@example.com"):
    print "Invalid email"

其他回答

from validate_email import validate_email
is_valid = validate_email('example@example.com',verify=True)
print(bool(is_valid))

参见validate_email文档。

检查电子邮件使用email_validator

from email_validator import validate_email, EmailNotValidError

def check_email(email):
    try:
        v = validate_email(email)  # validate and get info
        email = v["email"]  # replace with normalized form
        print("True")
    except EmailNotValidError as e:
        # email is not valid, exception message is human-readable
        print(str(e))

check_email("test@gmailcom")

发现这是一个实用的实现:

^[^@\s]+@[^@\s]+\.[^@\s]+$

The only really accurate way of distinguishing real, valid email addresses from invalid ones is to send mail to it. What counts as an email is surprisingly convoluted ("John Doe" <john.doe@example.com>" actually is a valid email address), and you most likely want the email address to actually send mail to it later. After it passes some basic sanity checks (such as in Thomas's answer, has an @ and at least one . after the @), you should probably just send an email verification letter to the address, and wait for the user to follow a link embedded in the message to confirm that the email was valid.

我在这里看到了很多复杂的答案。他们中的一些人,不知道简单,真实的电子邮件地址,或有假阳性。下面是测试字符串是否为有效电子邮件的最简单方法。它测试2和3个字母的TLD。现在技术上你可以有更大的,你可能希望增加3到4,5甚至10。

import re
def valid_email(email):
  return bool(re.search(r"^[\w\.\+\-]+\@[\w]+\.[a-z]{2,3}$", email))