是否有一个好方法来检查表单输入使用正则表达式,以确保它是一个正确的风格的电子邮件地址?从昨晚开始搜索,每个人都回答了关于这个话题的问题,如果它是一个子域名的电子邮件地址,似乎也有问题。
当前回答
import re
def email():
email = raw_input("enter the mail address::")
match = re.search(r'[\w.-]+@[\w.-]+.\w+', email)
if match:
print "valid email :::", match.group()
else:
print "not valid:::"
email()
其他回答
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.
发现电子邮箱:
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..
没有任何意义。即使您可以验证电子邮件地址在语法上是有效的,您仍然需要检查它是否没有输入错误,并且它实际上是发送给您认为的那个人的。唯一的方法就是给他们发一封电子邮件,让他们点击一个链接来验证。
因此,最基本的检查(例如,他们没有不小心输入他们的街道地址)通常就足够了。比如:它只有一个@符号,而且至少有一个。在@:后面的部分
[^@]+@[^@]+\.[^@]+
您可能还想禁止使用空格——可能有一些有效的电子邮件地址中有空格,但我从未见过,所以这是用户错误的可能性在您这边。
如果你想要完整的支票,看看这个问题。
更新:以下是如何使用任何这样的正则表达式:
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服务器以验证地址是否存在。不过,这仍然不能保证它属于正确的人。
from validate_email import validate_email
is_valid = validate_email('example@example.com',verify=True)
print(bool(is_valid))
参见validate_email文档。
如果你想从一个长字符串或文件中取出邮件,那么试试这个。
([^@|\s]+@[^@]+\.[^@|\s]+)
注意,当你的电子邮件地址前后都有空格时,这是有效的。如果你没有空间或有一些特殊的字符,那么你可以尝试修改它。
工作的例子:
string="Hello ABCD, here is my mail id example@me.com "
res = re.search("([^@|\s]+@[^@]+\.[^@|\s]+)",string,re.I)
res.group(1)
这将从该字符串中删除example@me.com。
另外,注意这可能不是正确答案……但我把它贴在这里是为了帮助像我这样有特殊要求的人
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录