看一个例子:
var re = /(\[#([0-9]{8})\])/g,
str = "[#12345678] [#87654321]",
match;
while (match = re.exec(str)) {
console.log(match[2]);
}
输出结果是匹配到两个分组的数据,也就是while 执行了两次:
如果想在while 循环中之前,判断一下字符串是否可以匹配这个正则的模式,使用 test()
var re = /(\[#([0-9]{8})\])/g,
str = "[#12345678] [#87654321]",
match;
if (re.test(str)) {
while (match = re.exec(str)) {
console.log(match[2]);
}
}
输出结果就少了第一个分组的匹配结果,while 只执行了一次:
原因是:RegExp 的lastIndex 属性用于规定下次检索的起始点,test() 方法也会修改下次检索的起始点
这里需要在test() 方法后,修改 lastIndex = 0
var re = /(\[#([0-9]{8})\])/g,
str = "[#12345678] [#87654321]",
match;
if (re.test(str)) {
re.lastIndex = 0
while (match = re.exec(str)) {
console.log(match[2]);
}
}