JavaScript正则表达式问题?
伊谢尔伦
伊谢尔伦 2017-04-11 11:07:21
[JavaScript讨论组]

有这样一个正则表达式 /.(w+)/g,exec一个字符串'a.b.c',结果是什么?不是得到.b和.c吗?

/\.(\w+)/g.exec('a.b.c')
伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回复(4)
天蓬老师
var reg = /\.(\w+)/g
undefined
var str = 'a.b.c';
undefined
reg.exec(str)
[".b", "b"]
reg.exec(str)
[".c", "c"]
reg.exec(str)
null


Return value

If the match succeeds, the exec() method returns an array and updates properties of the regular expression object. The returned array has the matched text as the first item, and then one item for each capturing parenthesis that matched containing the text that was captured.

If the match fails, the exec() method returns null.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec

高洛峰

虽然你加了g标志,但是exec每次执行还是只返回1个结果,不过会记录该次结果的index,之后继续执行exec的话,会继续进行捕获,直到没有捕获结果返回null,之后再执行的话会又重头开始捕获。

var reg = /\.(\w+)/g

reg.exec('a.b.c')
//[".b", "b"]
reg.exec('a.b.c')
//[".c", "c"]
reg.exec('a.b.c')
//null
reg.exec('a.b.c')
//[".b", "b"]
reg.exec('a.b.c')
//[".c", "c"]
reg.exec('a.b.c')
//null
PHP中文网
/\.(\w)/g.exec('a.b.c')    //  [".b", "b"]
'a.b.c'.match(/(\.\w+)/g)   // [".b", ".c"]
巴扎黑

正则捕获是 有懒惰性的,捕获到 一个能匹配上的 就不会 继续了。。但是 他会记录下 当前开始查找的str的index, 比如 第一次捕获的是 .b index是从0开始的 下次index 从3 开始,也就是第二个 . 直到找到null为止,当你继续捕获 ,index又会从0开始;
正则还有 贪婪性。。可以百度体会 一下

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

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