我正在Python中设置一个函数,以接收MM / DD / YYYY格式的日期,然后使用正则表达式对其进行验证。这就是我现在所拥有的:
def getdate():
date = raw_input("Please enter the date completed (MM/DD/YYY): ")
if re.match(r"\d{2}/\d{2}/\d{4}", date)
break
else:
print "Incorrect date format"
getdate()
系统不断返回语法错误,该错误指向“ if”行中的小括号。我似乎无法弄清楚它在考虑什么语法错误。我也尝试过此方法,但没有成功:
def getdate():
date = raw_input("Please enter the date completed (MM/DD/YYY): ")
valid = "(\d{2}/\d{2}/\d{4})"
if re.match(valid, date)
break
else:
print "Incorrect date format"
getdate()
这也会返回相同的错误。
谢谢。
最后需要一个冒号:
if re.match(r"\d{2}/\d{2}/\d{4}", date):
# here --^
Python使用冒号结束语句。
同样,如@RohitJain所述,使用递归请求重复输入也是一种不好的做法。您可能需要使代码如下所示:
def getdate():
date = raw_input("Please enter the date completed (MM/DD/YYY): ")
valid = "(\d{2}/\d{2}/\d{4})"
while not re.match(valid, date):
print "Incorrect date format"
date = raw_input("Please enter the date completed (MM/DD/YYY): ")
return date
此新代码使用循环,直到输入满足规范为止(即,re.match
返回匹配项)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句