我有以下正则表达式模式匹配所有以 URL 列表中的数字结尾的“行为”。
正则表达式 /\/ch(\d+)\/act(\d+)/gi
Javascript 代码
pageSrc[1] = "../ch01/index.html";
pageSrc[2] = "../ch01/act01/1.html";
pageSrc[3] = "../ch01/act01/2.html";
pageSrc[4] = "../ch01/act02/1.html";
pageSrc[5] = "../ch01/act02/2.html";
pageSrc[6] = "../ch01/actx/1.html";
var pattern = /\/ch(\d+)\/act(\d+)/gi;
for(var i=0; i<pageSrc.length; ++i){
var hasAct = pattern.test(pageSrc[i]);
console.log(hasAct);
}
预期结果与实际结果
| String | Expected Result | Actual Result |
| pageSrc[1] | false | false |
| pageSrc[2] | true | true |
| pageSrc[3] | true | *FALSE |
| pageSrc[4] | true | true |
| pageSrc[5] | true | *FALSE |
| pageSrc[6] | false | false |
我不确定为什么 pageSrc[3]
不会返回 true
。我在 gskinner.com 上使用了 regEx 测试器,它工作正常,这里是链接 http://gskinner.com/RegExr/?344ap
谁能帮我看看?提前致谢!
最佳答案
删除 g
标志。来自 the RegExp.test
documentation:
As with
exec
(or in combination with it),test
called multiple times on the same global regular expression instance will advance past the previous match.
在重用这样的模式时,您不希望进行全局搜索。
> var pageSrc = [];
> pageSrc[1] = "../ch01/index.html";
pageSrc[2] = "../ch01/act01/1.html";
pageSrc[3] = "../ch01/act01/2.html";
pageSrc[4] = "../ch01/act02/1.html";
pageSrc[5] = "../ch01/act02/2.html";
pageSrc[6] = "../ch01/actx/1.html";
var pattern = /\/ch(\d+)\/act(\d+)/i;
for(var i=0; i<pageSrc.length; ++i){
var hasAct = pattern.test(pageSrc[i]);
console.log(i, hasAct);
}
0 false
1 false
2 true
3 true
4 true
5 true
6 false
关于Javascript正则表达式匹配以数字结尾的字符串不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15401457/