正则表达式模式匹配从Javascript中的字符串中提取时间,从而产生意外结果

时间:2015-04-02 16:32:41

标签: javascript regex

我正在尝试匹配表示时间的可能方式。我试图匹配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'则没有。我无法弄清楚为什么会这样。任何帮助将受到高度赞赏。

1 个答案:

答案 0 :(得分:0)

这是因为在你的正则表达式中使用全局g标志并重复使用相同的正则表达式。 当在多个lastIndexg方法调用之间使用exec标记时,正则表达式对象会记住test

删除g标记,这将被修复。

或者在每次调用lastIndex之前,将此代码重置为exec属性:

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