我正在使用python 3.x。我有一个DOB帖子请求,用户可以输入YYYY格式的年份或DD / MM / YYYY格式的日期 有没有一种方法可以验证用户是否已按要求的格式输入DOB或提示他以正确的格式输入DOB。 我正在使用正则表达式
if re.match( "\d{4}", dob_check):
client_dob = dob_check
elif datetime.datetime.strptime(dob_check, "%d%d/%m%m/%Y%Y%Y%Y"):
client_dob = dob_check
else :
return return_aadhar_date_format
当我输入1891时,如果我输入的数字超过5则它也可以正确提取DOB,而不会接受。 但是当我输入的数字少于或等于3位数时,则会引发re.error
re.error:将组名“ d”重新定义为组2;是第1组
。但是我想提示用户以正确的格式输入DOB。这不是一个例外,它有一些包装错误。 另外,当我在2000年12月12日进入DOB时,它会引发re.error,因为我的猜测是它进入了第一个if块,并且执行在那里停止。
下面是我的方法
if len(dob_check) == 4:
client_dob = dob_check
elif datetime.datetime.strptime(dob_check, "%d/%m/%Y"):
client_dob = dob_check
else :
return correct_format
秒:
if len(dob_check) == 4:
try :
if len(dob_check) == 4:
client_dob = dob_check
else:
return correct_format
except:
return correct_format
elif datetime.datetime.strptime(dob_check, "%d/%m/%Y"):
client_dob = dob_check
else :
return correct_format
答案 0 :(得分:1)
请您尝试以下代码
if re.match( "^[1-9]\d{3}$", dob_check):
client_dob = dob_check
elif re.findall(r"[\d]{2}/[\d]{2}/[\d]{4}", dob_check):
client_dob = dob_check
else :
return incorrect_format
答案 1 :(得分:1)
为什么不只对两个验证都使用strptime
?
编辑:已经向我指出,它从未达到full_time
检查是否确实匹配,因此这是另一种尝试。
def is_datetime_match(s, pattern):
try:
datetime.datetime.strptime(s, pattern)
return True
except ValueError:
return False
if is_datetime_match(dob_check, '%Y') or is_datetime_match(dob_check, '%d/%m/%Y'):
client_dob = dob_check:
else:
return incorrect_format