如何检查有效的电子邮件地址? [英] How to check for valid email address?

查看:203
本文介绍了如何检查有效的电子邮件地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在一种使用正则表达式检查表单输入以确保它是正确样式的电子邮件地址的好方法?自昨晚以来一直在搜索,如果它是子域的电子邮件地址,则回答了有关该主题的人们疑问的每个人似乎也有问题.

Is there a good way to check a form input using regex to make sure it is a proper style email address? Been searching since last night and everybody that has answered peoples questions regarding this topic also seems to have problems with it if it is a subdomained email address.

推荐答案

没有意义.即使您可以验证该电子邮件地址在语法上是有效的,您仍然需要检查该电子邮件地址是否未键入错误,以及该地址是否确实发给了您认为确实有用的人.唯一的方法是向他们发送电子邮件,并让他们单击链接进行验证.

There is no point. Even if you can verify that the email address is syntactically valid, you'll still need to check that it was not mistyped, and that it actually goes to the person you think it does. The only way to do that is to send them an email and have them click a link to verify.

因此,最基本的检查(例如,他们没有意外输入街道地址)通常就足够了.像这样:它正好有一个@符号,并且在@之后的部分中至少有一个.:

Therefore, a most basic check (e.g. that they didn't accidentally entered their street address) is usually enough. Something like: it has exactly one @ sign, and at least one . in the part after the @:

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

您可能还想禁止使用空格-可能有有效的电子邮件地址,其中包含空格,但我从未见过,所以这是用户错误的可能性就在您身边.

You'd probably also want to disallow whitespace -- there are probably valid email addresses with whitespace in them, but I've never seen one, so the odds of this being a user error are on your side.

如果要进行完整检查,请查看这个问题.

If you want the full check, have a look at this question.

更新:以下是您可以使用任何此类正则表达式的方法:

Update: Here's how you could use any such regex:

import re

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

Python≥3.4具有 re.fullmatch re.match.

Python ≥3.4 has re.fullmatch which is preferable to re.match.

注意字符串前面的r;这样,您就无需两次逃脱.

Note the r in front of the string; this way, you won't need to escape things twice.

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

If you have a large number of regexes to check, it might be faster to compile the regex first:

import re

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

if not EMAIL_REGEX.match(email):
  # whatever


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


Another option is to use the validate_email package, which actually contacts the SMTP server to verify that the address exists. This still doesn't guarantee that it belongs to the right person, though.

这篇关于如何检查有效的电子邮件地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆