如何搜索正则表达式python

问题描述 投票:-1回答:1

我正在尝试为练习检查错误的输入格式创建错误处理程序。我查看了文档和示例文档,但我仍然在这里。我相信我正在寻找:(也尝试过一些变体)

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()

除非我没有办法使用in

python
1个回答
0
投票

您误读了文档,https://docs.python.org/3/library/re.html

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'

现在,将剩余时间与您所学到的相提并论!提示:其余时间从0开始。

© www.soinside.com 2019 - 2024. All rights reserved.