我正在尝试匹配表示时间的可能方式。我正在尝试匹配X,XX,XX:XX,X am,X pm,XXXX hr等,其中X是一个可能的数字,可以表示时间。
timereg = /([0-1][0-9]|2[0-3]|[1-9])[:s]*([0-5][0-9])?[s]*(am|pm|hrs|hr)?/gi
我尝试了以下正则表达式匹配的示例字符串,并在每次尝试下面的chrome控制台中看到了输出。
match = timereg.exec("Pick up at 5pm")
["5pm", "5", undefined, "pm"]
match = timereg.exec("Pick up at 5:30")
["5:30", "5", "30", undefined]
match = timereg.exec("Pick up kids at 5")
null
match = timereg.exec("Pick up kids at 15")
["15", "15", undefined, undefined]
match = timereg.exec("Pick up kids at 05")
["05", "05", undefined, undefined]
match = timereg.exec("Pick up kids at 20")
null
match = timereg.exec("Pick up kids at 21")
["21", "21", undefined, undefined]
match = timereg.exec("Pick up kids at 22")
null
match = timereg.exec("Pick up kids at 23")
["23", "23", undefined, undefined]
match = timereg.exec("Pick up kids at 1")
null
match = timereg.exec("Pick up kids at 2")
["2", "2", undefined, undefined]
match = timereg.exec("Pick up kids at 3")
null
match = timereg.exec("Pick up kids at 4")
["4", "4", undefined, undefined]
match = timereg.exec("Pick up kids at 5")
null
match = timereg.exec("Pick up kids at 6")
["6", "6", undefined, undefined]
我看到"21"、"23"、"2"、"4"、"6"匹配,而"20"、"22"、"1"、"3"、"5"不匹配。我不明白为什么会这样。如有任何帮助,我们将不胜感激。
这是由于在正则表达式中使用了全局g
标志,并重复使用相同的正则表达式。Regex对象在多个exec
或test
方法调用之间与g
标志一起使用时会记住lastIndex
。
删除g
标志,这将得到修复。
或者在每次调用exec
之前放置此代码以重置lastIndex
属性:
timereg.lastIndex = 0;
match = timereg.exec("Pick up kids at 20");