var str="1 plus 2 equal 3";
x=str.match(/\d+/g);
y=/\d+/g.exec(str);
document.write(x+"<br/>");//1,2,3
document.write(y+"<br/>");//1
y=/\d+/g.exec(str);
document.write(y+"<br/>");//1??应该是2??
y=/\d+/g.exec(str);
document.write(y+"<br/>");//1??应该是3啊??
巴扎黑2017-04-10 17:11:08
var str="1 plus 2 equal 3";
rex = /\d+/g;
y=rex.exec(str); // 1
console.log(y);
console.log(rex.lastIndex);
y=rex.exec(str); // 2
console.log(y);
console.log(rex.lastIndex);
y=rex.exec(str); // 3
console.log(y);
console.log(rex.lastIndex);
要这样写,你那种写法每次都是一个新的RegExp对象,所以三次调用都是取的第一个匹配结果
ringa_lee2017-04-10 17:11:08
var str="1 plus 2 equal 3";
x=str.match(/\d+/g);
console.log(x);//1,2,3
y=/\d+/g.exec(str);
console.log(y);//1
y=/\d+/g.exec(str);
console.log(y);//1??应该是2??
y=/\d+/g.exec(str);
console.log(y);//1??应该是3啊??
每次执行exec方法是正则表达式都是一个新的和之前的不同,所以它们之间是无关的,匹配的lastIndex也不会传递下去
要想输出其期望的要这样修改:
var str="1 plus 2 equal 3";
x=str.match(/\d+/g);
console.log(x);//1,2,3
var myRegExp=/\d+/g;
y= myRegExp.exec(str);
console.log(y);//1
y= myRegExp.exec(str);
console.log(y);//2
y= myRegExp.exec(str);
console.log(y);//3