JavaScript正则表达式问题?

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

/\.(\w+)/g.exec('a.b.c')
阅读 3.8k
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
/\.(\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开始;
正则还有 贪婪性。。可以百度体会 一下

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题