我有一串用逗号和1个空格分隔的电子邮件:
string_of_emails = "email1@company.com, email2@company.com, email3@company.com, ... , email999@company.com"
我想对该字符串运行一个验证测试,以确保该字符串确实来自上述格式。
含义-检查每封电子邮件是否有效(user@domain.com)+每封电子邮件用逗号和1个空格分隔+最后一封电子邮件不应该有逗号。
您可以首先将字符串转换为列表:
emails = string_of_emails .split(", ")
之后,您可以为每封单独的电子邮件进行自己的regex检查,也可以使用众多可用软件包中的一个为您进行检查:Python电子邮件验证器
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
我只想分享一个大致的想法。。。
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("Errortt:: 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 entryt::" + 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 entryt::" + email + ":: make sure it follows the rule!")
else:
print("Valid entryt::" + 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())