带有/g的Javascript Regex文字多次使用 [英] Javascript Regex literal with /g used multiple times

查看:31
本文介绍了带有/g的Javascript Regex文字多次使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Javascript Regexp.exec函数时遇到了一个奇怪的问题.在新的(我想是...)regexp对象上多次调用该函数时,它每两个就会工作一次.我根本不明白为什么!

I have a weird issue working with the Javascript Regexp.exec function. When calling multiple time the function on new (I guess ...) regexp objects, it works one time every two. I don't get why at all!

这是一个小循环示例,但在函数中使用一次并多次调用时,它会执行相同的操作.

Here is a little loop example but it does the same thing when used one time in a function and called multiple times.

for (var i = 0; i < 5; ++i) {
  console.log(i, (/(b)/g).exec('abc'));
}

> 0 ["b", "b"]
> 1 null
> 2 ["b", "b"]
> 3 null
> 4 ["b", "b"]

删除/g时,它恢复正常.

When removing the /g, it gets back to normal.

for (var i = 0; i < 5; ++i) {
  console.log(i, (/(b)/).exec('abc'));
}             /* no g ^ */

> 0 ["b", "b"]
> 1 ["b", "b"]
> 2 ["b", "b"]
> 3 ["b", "b"]
> 4 ["b", "b"]

我猜有一个优化,保存了regexp对象,但这似乎很奇怪.

I guess that there is an optimization, saving the regexp object, but it seems strange.

此行为在Chrome 4和Firefox 3.6上相同,但其工作方式与IE8中的(I)相同.我相信这是有意的,但我找不到那里的逻辑,也许您将能够为我提供帮助!

This behaviour is the same on Chrome 4 and Firefox 3.6, however it works as (I) expected in IE8. I believe that is intended but I can't find the logic in there, maybe you will be able to help me!

谢谢

推荐答案

/g

/g 启用全局"匹配.使用 replace()方法时,请指定此修饰符以替换所有匹配项,而不是仅替换第一个匹配项.

/g enables "global" matching. When using the replace() method, specify this modifier to replace all matches, rather than only the first one.

我想在捕获之后,内部javascript会保留匹配,因此它可以恢复匹配,因此返回 null ,因为 b 在代码中仅出现一次主题.比较:

I'd imagine internally javascript holds the matching after the capture, so it would be able to resume matching and therefore null is returned since b occur only once in the subject. Compare:

for (var i = 0; i < 5; ++i) {
  console.log(i +'    ' + (/(b+)/g).exec("abbcb"));
}

返回:

0 bb,bb
1 b,b
2 null
3 bb,bb
4 b,b

这篇关于带有/g的Javascript Regex文字多次使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆