【问题标题】:Python check that string of emails list (e.g. "email1, email2, email3,...") is validPython 检查电子邮件列表字符串(例如“email1,email2,email3,...”)是否有效
【发布时间】:2019-05-14 12:07:09
【问题描述】:

我有一串用逗号和 1 个空格分隔的电子邮件:

string_of_emails = "email1@company.com, email2@company.com, email3@company.com, ... , email999@company.com"

我想对该字符串进行验证测试,以确保该字符串确实来自上述格式。

含义 - 检查每封电子邮件是否有效 (user@domain.com) + 每封电子邮件以逗号和 1 个空格分隔 + 最后一封电子邮件不应有逗号。

【问题讨论】:

  • 如果一封电子邮件没有所需的格式,输出是什么?
  • 您将不得不编写一些代码。

标签: python string validation email dns


【解决方案1】:

可以先将字符串转为列表:

emails = string_of_emails .split(", ")

之后,您可以对每封电子邮件进行自己的正则表达式检查,也可以使用众多可用的软件包之一为您执行此操作: Python Email Validator

for mail in emails:
    # do your own regex check here
    # OR
    # Use the email validator like this
    v = validate_email(email) # function from the email validator

【讨论】:

    【解决方案2】:

    只是想分享一个粗略的想法......

    import re
    soe = "abc_123@123.com ,you@yahoo.com , we@gmail.co.uk, gmail.com, me@outlook.com ,"
    soel = soe.split(',')
    
    #first entry cannot have space
    if soel[0].count(" ")!=0 :
        print("Error\t\t:: First entry cannot contain space!")
    #then, all subsequent must start with and contain exactly one space, along with a valid email
    for email in soel[1:]:
        if email.count(" ") > 1:
            print("Invalid entry\t::" + email, ":: too many spaces")
            continue
        #simple email regex (with a single space in front)
        match = re.search(r' ([\w\.-]+)@([\w\.-]+)', email)
        if match == None:
            print("Invalid entry\t::" + email + ":: make sure it follows the rule!")
        else:
            print("Valid entry\t::" + email)
    

    或了解更多详情,

    import re
    soe = " abc_123@123.com,you@yahoo.com , we@gmail.co.uk, gmail.com, me@outlook.com ,"
    soel = soe.split(',')
    
    end = len(soel)
    if soel[-1].strip()=='':
        print("Error:: Comma near the end of string!")
        end -= 1
    if soel[0].count(" ")>0:
        print("Error:: First entry cannot contain space!")
    for email in soel[1:end]:
        if email.count(" ") != 1 :
            print("Error:: " + email + " :: too many spaces!")
            continue
        if not email.startswith(" "):
            print("Error:: " + email + " :: one space is needed after comma!")
            continue
        #simple email regex
        match = re.search(r'([\w\.-]+)@([\w\.-]+)', email)
        if match != None:
            print("Correct format: " + match.group())
    

    【讨论】:

    • 您的解决方案很好,但在验证电子邮件地址时需要考虑很多问题。必要的正则表达式模式通常非常广泛,所以我总是倾向于使用专门用于此任务的包。例如,我在答案中链接的工具的默认配置甚至会检查顶级域是否有效。但是,这需要 Internet 连接,但可以禁用此选项。
    猜你喜欢
    • 2011-10-07
    • 2013-03-12
    • 2019-10-06
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多