Python - 简单的电子邮件验证脚本

时间:2021-05-21 06:01:04

标签: python string validation input

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

我可以弄清楚验证“@”符号,但我似乎无法弄清楚如何实现它以验证“@”将字符串分成 2 个部分。老实说,我不知道从哪里开始。

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

1 个答案:

答案 0 :(得分:2)

可能最简单的处理方法是使用正则表达式 (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