首先让我们看看你做错了什么:
13am-10pm(这不应该匹配,但它匹配并创建 4 个匹配组 3、am、10、pm)
它只匹配正确的时间,例如上午 111 点或下午 13 点等应被视为不匹配。
这匹配,因为您允许在此处匹配单个数字 [1-9]:(1[012]|[1-9])。
为了解决这个问题,您应该允许一个 [1-9] 数字或 1 + [0-2]。由于我们不知道正则表达式何时开始,我们将使用一些单词边界来确保我们有一个“单词开始”。
由于您不想捕获数字而是整个时间加上 am|pm 您可以使用非捕获组:
\b((?:1[0-2]|[1-9])
然后只需重复我们自己并添加一个破折号:
\b((?:1[0-2]|[1-9])[ap]m)-((?:1[0-2]|[1-9])[ap]m)
关于第 3 点。嗯,是的,您可以使用正则表达式来执行此操作,但是您最好在获得第 1 组和第 2 组后简单地添加一个逻辑检查,以查看时间范围是否真的有意义。
总而言之,这就是你得到的:
# \b((?:1[0-2]|[1-9])[ap]m)-((?:1[0-2]|[1-9])[ap]m)
#
#
# Assert position at a word boundary «\b»
# Match the regular expression below and capture its match into backreference number 1 «((?:1[0-2]|[1-9])[ap]m)»
# Match the regular expression below «(?:1[0-2]|[1-9])»
# Match either the regular expression below (attempting the next alternative only if this one fails) «1[0-2]»
# Match the character “1” literally «1»
# Match a single character in the range between “0” and “2” «[0-2]»
# Or match regular expression number 2 below (the entire group fails if this one fails to match) «[1-9]»
# Match a single character in the range between “1” and “9” «[1-9]»
# Match a single character present in the list “ap” «[ap]»
# Match the character “m” literally «m»
# Match the character “-” literally «-»
# Match the regular expression below and capture its match into backreference number 2 «((?:1[0-2]|[1-9])[ap]m)»
# Match the regular expression below «(?:1[0-2]|[1-9])»
# Match either the regular expression below (attempting the next alternative only if this one fails) «1[0-2]»
# Match the character “1” literally «1»
# Match a single character in the range between “0” and “2” «[0-2]»
# Or match regular expression number 2 below (the entire group fails if this one fails to match) «[1-9]»
# Match a single character in the range between “1” and “9” «[1-9]»
# Match a single character present in the list “ap” «[ap]»
# Match the character “m” literally «m»