您的位置:首页 > Web前端 > JavaScript

JavaScript中match方法与exec方法的异同

2016-07-21 16:03 661 查看
[code=language-javascript]var someText="web2.0 .net2.0";
var pattern=/(\w+)(\d)\.(\d)/g;
var outCome_exec=pattern.exec(someText);
var outCome_matc=someText.match(pattern);

[code=language-javascript]str.match(reg);
reg.exec(str);

如上段代码所示,两者的调用方式不同,match方法是字符串调用的方法,而exec方法是正则表达式对象调用的方法;

两者的返回结果都是数组,既有相同之处也有不同之处。

当正则表达式没有g时,两者返回结果一致,请看下段代码:

[code=language-javascript]var someText="web2.0 .net2.0";
var pattern=/(\w+)(\d)\.(\d)/;
var outCome_exec=pattern.exec(someText);
var outCome_matc=someText.match(pattern);
console.log(outCome_exec[0],outCome_exec[1]);//web2.0 web
console.log(outCome_matc[0],outCome_matc[1]);//web2.0 web

当没有加g时

两者都只是搜索到第一个匹配项后就返回匹配到的值存在数组的下标为0的位置;

其余位置分别放置正则表达式中特别选中的数据;

并且index属性值均为第一个匹配项的下标位置;

下段代码为返回的数组模式和属性值:

[code=language-javascript]//arr:[kword,$1,$2,...]
console.log(outCome_exec.index);//0
console.log(outCome_matc.index);//0
console.log(pattern.lastIndex);//0

当正则表达式加上g时

match返回装有所有匹配到的值的数组,但是没有index属性,返回的数组如下:

[code=language-javascript]arr:[kword1,kword2,kword3,...]

exec则是依次查找str中符合reg要求的第一个关键词,通过reg.lastIndex属性控制下一次查找的位置

循环调用exec

执行分3步:

1、将本次找到的关键词保存在数组的第一个元素 arr:[kword,$1,$2]

2、将本次找到的关键词的位置保存在index arr.index

3、将reg对象的lastIndex属性设置为index之后,reg.lastIndex规定下次从哪个位置开始

每次返回的数组即是arr:[kword,$1,$2];

代码如下:

[code=language-javascript]var someText="web2.0 net2.0";
var pattern=/(\w+)(\d)\.(\d)/g;//加g
var result;
while((result=pattern.exec(someText))!==null){
console.log(result[0]);//web2.0     net2.0
console.log(result[1]);//web        net
console.log(result.index);//0       7
console.log(pattern.lastIndex);//6  13
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: