var regexAbc = /a(b)c/gi
console.log(regexAbc.exec("abc")) // ["abc", "b"]
console.log(regexAbc.exec("abc")) // null
console.log(regexAbc.exec("abc")) // ["abc", "b"]
console.log(regexAbc.exec("abc")) // null
为什么会出现这样结果不一样的情况
附送参考链接:
http://stackoverflow.com/questions/11477415/why-does-javascripts-regex-exec-not-always-return-the-same-value
http://stackoverflow.com/questions/4724701/regexp-exec-returns-null-sporadically
http://stackoverflow.com/questions/10167323/regexp-exec-returns-null-when-called-repeatedly-in-firefox
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
javascript 的正则表达式是有状态的。尤其是
exec方法,是有副作用的。当其匹配成功的时候reg.lastIndex会被改变。因此导致了间隔的返回null的情况每次匹配完可以通过这样手动重置,以保证下一次匹配的结果是正常的
尤其是在循环中使用同一只正则表达式的时候,尤其需要注意这一点