[英]How to search for regex pattern python
我正在尝试为检查正确输入格式的练习创建错误处理程序。 我查看了文档和 SO 示例,但我仍然在这里。 我相信我正在寻找:(也尝试了一些变体)
check_time = re.compile('^[0-1][0-9]:[0-5][0-9] ([A|a]|[P|p][M|m])')
但我的测试用例失败了。 要求用户输入的代码:
import re
class CivilianTime:
def __init__(self):
# no error handling yet
self.civ_time = input('Enter the time in (XX:XX A/PM) format.\n')
check_time = re.compile('1[0-2]:[0-5][0-9] AM | 1[0-2]:[0-5][0-9] PM')
if check_time != self.civ_time:
self.civ_time = input('Enter the time in (XX:XX A/PM) format.\n')
# if PM, strip time to numerical values and add 1200
# if AM, strip time to numerical values
def time_converter(self):
if self.civ_time[-2] == 'P':
strip_time = self.civ_time.strip(" PM")
strip_time = strip_time.replace(':', '')
strip_time = int(strip_time) + 1200
print(strip_time)
else:
strip_time = self.civ_time.strip(' AM')
strip_time = strip_time.replace(':', '')
print(strip_time)
c = CivilianTime()
c.time_converter()
结果:
Enter the time in (XX:XX A/PM) format.
1212 am
Enter the time in (XX:XX A/PM) format.
1212pm
1212pm
当输入不是所需格式时,我想再次看到它要求时间。 即使没有空间,它也在运行 function。 除非我有办法in
.
您误读了文档https://docs.python.org/3/library/re.html
You are on the right track. When you use or
You are on the right track. When you use or
|` 时,你必须重写整个表达式。 因此,首先一次匹配 1 小时,然后在多行代码中简单地测试所有案例。 在您完全理解正则表达式之前,不要尝试对其进行衬里。
12:00 AM 和 11:00 AM 和 10:00 AM = 1[0-2]:[0-5][0-9] AM
现在要匹配 PM 你必须或|
整个表达式。 所以, matcher = '1[0-2]:[0-5][0-9] AM | 1[0-2]:[0-5][0-9] PM'
matcher = '1[0-2]:[0-5][0-9] AM | 1[0-2]:[0-5][0-9] PM'
现在将剩余时间与您所学的内容相匹配:提示。 小时的 rest 从 0 开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.