javascript - 正则表达式exec一个神秘的小问题
PHPz
PHPz 2017-04-10 16:59:00
[JavaScript讨论组]
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

PHPz
PHPz

学习是最好的投资!

全部回复(1)
巴扎黑

A JavaScript RegExp object is stateful.

When the regex is global, if you call a method the same regex object, it will start from the index past the end of the last match.

When no more matches are found, the index is reset to 0 automatically.

javascript 的正则表达式是有状态的。尤其是exec方法,是有副作用的。当其匹配成功的时候reg.lastIndex会被改变。因此导致了间隔的返回null的情况

To reset it manually, set the lastIndex property.

每次匹配完可以通过这样手动重置,以保证下一次匹配的结果是正常

reg.lastIndex = 0;

尤其是在循环中使用同一只正则表达式的时候,尤其需要注意这一点

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号