我正在制定检查字符串(电子邮件)的算法——比如“电子邮件地址有效”,但它们是规则。电子邮件的第一部分必须是包含 1-8 个字符的字符串(可以包含字母、数字、下划线 [_]...电子邮件包含的所有部分),@ 之后电子邮件的第二部分有具有 1-12 个字符的字符串(也包含所有合法表达式)并且必须以顶级域 .com 结尾
email = raw_input ("Enter the e-mail address:")
length = len (email)
if length > 20
print "Address is too long"
elif lenght < 7:
print "Address is too short"
if not email.endswith (".com"):
print "Address doesn't contain correct domain ending"
try:
first_part = len (splitting[0])
second_part = len(splitting[1])
account = splitting[0]
domain = splitting[1]
list = "abcdefghijklmopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_."
for c in account:
if c not in list:
print "Invalid char", "->", c,"<-", "in account name of e-mail"
for c in domain:
if c not in list:
print "Invalid char", "->", c,"<-", "in domain name of e-mail"
if first_part == 0:
print "You need at least 1 character before the @"
elif first_part> 8:
print "The first part is too long"
if second_part == 4:
print "You need at least 1 character after the @"
elif second_part> 16:
print "The second part is too long"
except IndexError:
print ""The address must consist of 2 parts connected with symbol @,\
and ending must be .com"
if first_part > 0 and first_part < 8 and second_part >4 and second_part < 16:
print "Valid e-mail address"
最佳答案
import re
address = 'test@gmail.com'
if re.match(r'^[a-z0-9_]{1,8}@[a-z0-9_]{1,8}\.com$', address, re.IGNORECASE):
print 'valid'
else:
print 'invalid'
一个较短的正则表达式(如注释所示)是 r'^\w{1,8}@\w{1,8}\.com$'
我不知道那是不是你老师的目标,但知道正则表达式总是好的:)
关于python - 在 Python 中过滤字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11054478/