Regex模式匹配,从Javascript中的字符串中提取时间,结果出乎意料

Regex pattern match to extract time from a string in Javascript giving unexpected results

本文关键字:提取 取时间 结果 出乎意料 字符串 Javascript Regex 模式匹配      更新时间:2023-09-26

我正在尝试匹配表示时间的可能方式。我正在尝试匹配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对象在多个exectest方法调用之间与g标志一起使用时会记住lastIndex

删除g标志,这将得到修复。

或者在每次调用exec之前放置此代码以重置lastIndex属性:

timereg.lastIndex = 0;
match = timereg.exec("Pick up kids at 20");