Python简单电子邮件验证脚本

2024-04-24 18:51:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要编写一个脚本来“验证”电子邮件地址,方法是接受用户输入,并检查字符串是否被“@”符号分成两段(老实说,这毫无意义——我知道)

我可以验证'@'符号,但我似乎不知道如何实现它来验证'@'是否将字符串分成两段。我真的不知道从哪里开始

print ("\n––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––")
print ("\n Welcome to my Email Address Validator!")
print (" You can use this tool to check the validation of email addresses.")
print("\n Please input the email address that you would like to validate.")
print ("\n––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––")

def email_check():
    
    address = str(input("\n Email Address:  "))

    if "@" in address:
        print ("\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .")
        print ("\n This is a valid email address!")
        print ("\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .")
        return email_check()

    else:
        print ("\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .")
        print ("\n This is an invalid email address!\n No @ symbol identified!")
        print ("\n. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .")
        return email_check()


email_check()

Tags: theto字符串脚本inputreturnisaddress
3条回答

您可以使用str.split(),也可以使用正则表达式

https://www.geeksforgeeks.org/python-string-split/

但是,不必检查电子邮件地址中是否有空格,只需使用str.split(“”)查找并删除它们,然后创建有效的电子邮件即可

可以使用正则表达式检查字符串中间是否有“@”符号:

import re

address = str(input("\n Email Address:  "))

if(re.match('.+@.+', address)):
    print("address has '@' in the middle")

.+@.+是一个正则表达式,用于检查字符串在符号“@”前后是否有1个或多个字符(.+

要检查字符串是否不包含空格,只需使用not in运算符:

if(' ' not in address):
    print("address does not contain whitespaces")

处理这个问题的最简单方法可能是使用正则表达式(regex),因为尽管可以使用原始Python(即使用str.split()并检查返回值),但您的代码将更难解析

以下是只应与有效电子邮件地址匹配的正则表达式:

^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$

您可以使用this工具对您的案例进行测试。当您将鼠标悬停在表达式的每个组件上时,它还提供了它们的解释

在使用中:

import re


def valid_email(address):
    valid_email_regex = '^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$'
    if not re.search(valid_email_regex, address):
        return False
    return True

相关问题 更多 >