import re
inserts = [
'aBC123',
'ABC 123',
'i like pie.',
'123abc',
]
for i in inserts:
if re.match('^[a-zA-Z]+[0-9]*$', i):
# if re.match('^[a-zA-Z0-9]*$', i): #leaving my old error visible as a testament to the importance of reading the spec carefully.
print('insert', i)
# call insert function
else:
print('NOT inserting', i)
# do whatever
from string import letters, digits
from itertools import chain
while True:
user_input = input('Insert first name: ')
if all(c in digits for c in user_input) or #invalid if only numbers
any(c not in chain(letters,digits) for c in user_input): #invalid if something else than letters+numbers
print 'name: ' + user_input + '** not allowed **'
else:
print 'name: ' + user_input + '** allowed **'
break
Code:
or i in "5363737","Bird1 !", "Bird1", "Bird1923812", "Bird":
mo = re.match(r'([A-Za-z]+[0-9]*)$',i)
if mo:
print("allowed {}".format(mo.group(0)))
else:
print("not allowed {}".format(i))
not allowed 5363737
not allowed Bird1 !
allowed Bird1
allowed Bird1923812
allowed Bird
# if needed, as stated in the comment char+number+char, number+char,
# number+char+number.
for i in "536cat3737","Bird1 !", "Bird1", "Bird1923812bird", "Bird","777Bird":
mo = re.match(r'([A-Za-z]*[0-9]+[A-Za-z]+|\d+[A-Za-z]+\d+)$',i)
if mo:
print("allowed {}".format(mo.group(0)))
else:
print("not allowed {}".format(i))
无论你用什么“插入”都可能有它自己的验证函数,但是如果没有,那就是一个简单的正则表达式来过滤。在
没有
re
模块:相关问题 更多 >
编程相关推荐