我写了以下正则表达式
(1[012]|[1-9])(am|pm)\-(1[012]|[1-9])(am|pm)
匹配以下类型的时间格式:
7am-10pm (matches correctly and creates 4 match groups 7, am, 10, pm)
13am-10pm (this should not be matched, however it matches and creates 4 match groups 3, am, 10, pm)
10pm (this doesn't match as expected because it doesn't specify the time range end)
111am-10pm (this should not be matched, however it matches and creates 4 match groups 11, am, 10, pm)
如何改善我的正则表达式,这样我就不需要重复数字和am / pm模式,还可以进行以下操作:
它仅捕获时间范围成分,例如上午7点至上午10点,因此应该只有2个匹配组,上午7点,上午10点。
它仅匹配适当的时间,例如111am或13pm等,应视为不匹配。
我不知道是否可以使用正则表达式,但是我们可以使正则表达式匹配正确的时间范围,例如7 am-1pm应该匹配,但是4 pm-1pm应该被视为不匹配吗?
注意:我正在使用Ruby 2.2.1
谢谢。
首先,让我们看看您做错了什么:
上午13点至晚上10点(不应该匹配,但是它会匹配并创建4个匹配组3,am,10,pm)
它仅匹配适当的时间,例如111am或13pm等,应视为不匹配。
之所以匹配,是因为您可以在此处匹配单个数字[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»
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句