我正在尝试确定字符串是否是电子邮件。要求当然是@ email.com,首字母必须是大写字母,并且必须是字母数字,除了@和点号。我正在寻找的是是否有一种方法可以检查电子邮件是否为字母数字,但句号和@
除外。我想要的是,如果且仅当第一个字母为大写字母时,代码具有@ emuail.com,并且它是字母数字,但@和句点除外,代码将为电子邮件返回True。我想要的是一种检查字母数字的解决方案,除了@和电子邮件的@ emauil.com部分中的句点。
我以为我可以在@email部分分开电子邮件,并检查@ismail之前的所有内容是否为.isalnum,但我只是想看看是否有更简单的方法。
这是我当前的代码,由于@和句点,当然返回所有False:
emails = ['[email protected]', '[email protected]', '[email protected]']
result = []
for idx, email in enumerate(emails):
if '@emuail.com' in email and email[0].isupper() and email.isalnum():
result.append(True)
else:
result.append(False)
print(result)
[进行稍微复杂的字符串搜索/测试时,通常使用regular expressions更好(更易读,更灵活)。
import re
# from https://emailregex.com/
email_pattern = re.compile(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)")
emails = ['[email protected]', '[email protected]', '[email protected]']
for email in emails:
if email_pattern.match(email):
print(email)
请注意,电子邮件地址中允许使用连字符,但如果出于某些原因要禁止使用连字符,请从正则表达式中将它们删除。
此生成器将返回有效的电子邮件。如果需要更多规则,请将其添加到条件中。
emails = ['[email protected]', '[email protected]', '[email protected]']
[i for i in emails if '@' in i and i[-4:] == '.com' and i.split('@')[0].isalnum() and '@' is not i[-5]]