我希望检查用户输入的日期格式是否与以下格式相匹配:
我将使用以下正则表达式进行匹配:
Jan 5 2018 6:10 PM
Month: First letter should be caps, followed 2 more in small. (total 3 letters)
<Space>: single space, must exist
Date: For single digit it should not be 05, but 5
<Space>: single space, must exist
Hour: 0-12, for single digit it should not be 06, but 6
Minute: 00-59
AM/PM
我将使用以下正则表达式进行匹配:
我正在使用以下正则表达式并尝试匹配:
import re,sys
usr_date = str(input("Please enter the older date until which you want to scan ? \n[Date Format Example: Jan 5 2018 6:10 PM] : "))
valid_usr_date = re.search("^(\s+)*[A-Z]{1}[a-z]{2}\s{1}[1-31]{1}\s{1}[1-2]{1}[0-9]{1}[0-9]{1}[0-9]{1}\s{1}[0-12]{1}:[0-5]{1}[0-9]{1}\s{1}(A|P)M$",usr_date,re.M)
if not valid_usr_date:
print ("The date format is incorrect. Please follow the exact date format as shown in example. Exiting Program!")
sys.exit()
即使按照正确的格式,也会出现“语法错误”的提示。我做错了什么。
[1-31]
匹配1
、2
或3
。字符类并不像你想象的那样工作。 - Wiktor Stribiżewdatetime.strptime
可以轻松解析的格式吗? - Reut Sharabanidatetime.strptime
解析了日期的不同部分,但这在我的程序中还很遥远。在进入那里之前,我想保持一个验证函数,在那里我验证来自用户的所有输入,如果无法验证,则程序退出并且不再继续。此外,我不想将程序模块绑定到多个try: except:
上。相反,我正在使用sys.excepthook
来捕获所有异常。 - dig_123