Python检查电子邮件列表字符串(例如“email1,email2,email3,…”)是否有效

2024-10-01 05:06:07 发布

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

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

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

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

意思-检查每封邮件是否有效(user@domain.com)+每封邮件用逗号和1个空格隔开+最后一封邮件不应该有逗号。你知道吗


Tags: of字符串comstring电子邮件格式邮件company
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())

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

emails = string_of_emails .split(", ")

之后,您可以为每个电子邮件执行自己的regex检查,也可以使用许多可用软件包中的一个来执行此操作: 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

相关问题 更多 >