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


当前回答

在电子邮件输入上使用此过滤器掩码: emailMask: / (\ w .\-@'"!#$%&'*+/=?^ _{|} ~) /我

其他回答

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

没有任何意义。即使您可以验证电子邮件地址在语法上是有效的,您仍然需要检查它是否没有输入错误,并且它实际上是发送给您认为的那个人的。唯一的方法就是给他们发一封电子邮件,让他们点击一个链接来验证。

因此,最基本的检查(例如,他们没有不小心输入他们的街道地址)通常就足够了。比如:它只有一个@符号,而且至少有一个。在@:后面的部分

[^@]+@[^@]+\.[^@]+

您可能还想禁止使用空格——可能有一些有效的电子邮件地址中有空格,但我从未见过,所以这是用户错误的可能性在您这边。

如果你想要完整的支票,看看这个问题。


更新:以下是如何使用任何这样的正则表达式:

import re

if not re.match(r"... regex here ...", email):
  # whatever

Python≥3.4有re.fullmatch,它比re.match更可取。

注意字符串前面的r;这样,你就不需要两次逃避了。

如果你有大量的正则表达式要检查,首先编译正则表达式可能会更快:

import re

EMAIL_REGEX = re.compile(r"... regex here ...")

if not EMAIL_REGEX.match(email):
  # whatever

另一种选择是使用validate_email包,它实际联系SMTP服务器以验证地址是否存在。不过,这仍然不能保证它属于正确的人。

发现电子邮箱:

import re 
a=open("aa.txt","r")
#c=a.readlines() 
b=a.read()
c=b.split("\n")
print(c)
  for d in c: 
    obj=re.search(r'[\w.]+\@[\w.]+',d)
    if obj:
      print(obj.group())  
#for more calcification click on image above..

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

# 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)