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


当前回答

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

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

其他回答

检查电子邮件使用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")

电子邮件地址并不像看上去那么简单!例如,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"

电子邮件验证

import re
def validate(email): 
    match=re.search(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9]+\.[a-zA-Z0-9.]*\.*[com|org|edu]{3}$)",email)
    if match:
        return 'Valid email.'
    else:
        return 'Invalid email.'

我发现了一个很好的(经过测试的)方法来检查有效的电子邮件地址。我把代码粘贴在这里:

# here i import the module that implements regular expressions
import re

# here is my function to check for valid email address
def test_email(your_pattern):
  pattern = re.compile(your_pattern)
  # here is an example list of email to check it at the end
  emails = ["john@example.com", "python-list@python.org", "wha.t.`1an?ug{}ly@email.com"]
  for email in emails:
    if not re.match(pattern, email):
        print "You failed to match %s" % (email)
    elif not your_pattern:
        print "Forgot to enter a pattern!"
    else:
        print "Pass"

# my pattern that is passed as argument in my function is here!
pattern = r"\"?([-a-zA-Z0-9.`?{}]+@\w+\.\w+)\"?"   

# here i test my function passing my pattern
test_email(pattern)
from validate_email import validate_email
is_valid = validate_email('example@example.com',verify=True)
print(bool(is_valid))

参见validate_email文档。