JavaScript正则表达式.match有缺陷? [英] Javascript regex.match defective?
问题描述
if(rePrv.test(h)|| rePrv.test(h))
$ c现在如果我只有 if(rePrv.test(h))
我有时候得到一个错误的(不正确的)。但是用||我得到正确的结果。它吹我的大脑。到底是怎么回事?有人可以解释吗?这发生在firefox 8,11(便携式)和chrome 17.0下。
这是我的用户脚本代码
// == UserScript ==
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
// == / UserScript ==
var re = / \ /?docs\ / \d + / gi;
var rePrv = / \ /?docs\ / \ d + \ / private / gi;
var prvls =;
var publs =;
$('a')。each(function(i,e){
var h = $(this).attr('href');
if(h == undefined)
return;
if(re.test(h)){
if(rePrv.test(h)|| rePrv.test(h)){
prvls + =http ://www.domain.com/+ h +< br /> \\\
;
}
else {
publs + =http://www.domain。 com /+ h +< br /> \\\
;
}
}
});
解决方案 RegExp 有一个 internal state , G。 lastIndex
指定开始下一个匹配的索引。如果你打电话给 exec
或使用 exec
内部的任何其他方法,如 test
,那么当使用全局匹配。因此,多次调用 test
可以在每次调用时获得不同的结果:
var str ='foobar foobar';
var re = / foo / g;
alert(re.test(str)&& re.lastIndex); // re.lastIndex === 3
alert(re.test(str)&& re.lastIndex); // re.lastIndex === 10
I promise you I am not lying. There is one strange line in this userscript. Its
if(rePrv.test(h)||rePrv.test(h))
Now if i only have if(rePrv.test(h))
I sometimes get a false (incorrectly). However with the || i get the correct results. Its blowing my brain. What is going on? Can someone explain? It happens in under firefox 8, 11(portable) and chrome 17.0.
This is my userscript code.
// ==UserScript==
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
// ==/UserScript==
var re=/\/?docs\/\d+/gi;
var rePrv=/\/?docs\/\d+\/private/gi;
var prvls="";
var publs="";
$('a').each(function(i, e){
var h = $(this).attr('href');
if(h==undefined)
return;
if(re.test(h)){
if(rePrv.test(h)||rePrv.test(h)){
prvls+="http://www.domain.com/"+h+"<br/>\n";
}
else {
publs+="http://www.domain.com/"+h+"<br/>\n";
}
}
});
解决方案 Each instance of RegExp has an internal state, e. g. lastIndex
that specifies the index at which to start the next match. If you call exec
or any other method that uses exec
internally like test
does, that state might change when using global matching. So calling test
multiple times can get you different results on each call:
var str = 'foobar foobar';
var re = /foo/g;
alert(re.test(str) && re.lastIndex); // re.lastIndex === 3
alert(re.test(str) && re.lastIndex); // re.lastIndex === 10
这篇关于JavaScript正则表达式.match有缺陷?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!