正则表达式中字符串模式匹配方法exec和match的区别

js正则表达式中字符串模式匹配方法exec()和match()的有相近的作用,但也存在一些需要注意的区别。

第一点!!!这是没有设置全局标志g的情况:exec专门为捕获组而设计,可接受一个参数,即要应用模式的字符串,然后返回一个数组(没有捕获组时,数组只包含一项,即第一个匹配项信息;有捕获组时,其他项是模式中的捕获组匹配的字符串。match也只接受一个参数,即一个正则表达式或regExp对象,返回的是一个数组,与exec相同。

var text="cat, bat, sat, fat";
var pattern=/.at/;

var matches=text.match(pattern);
var matches1=pattern.exec(text);
console.log(matches);
console.log(matches.index);
console.log(matches[0]);
       
console.log(matches1);
console.log(matches1.index);
console.log(matches1[0]);

console.log(pattern.lastIndex)

结果如下:

var text="cat, bat, sat, fat";
var pattern=/.(a)t/;

var matches=text.match(pattern);
var matches1=pattern.exec(text);
console.log(matches);
console.log(matches.index);
console.log(matches[0]);
       
console.log(matches1);
console.log(matches1.index);
console.log(matches1[0]);

 console.log(pattern.lastIndex);
结果如下:



第二点!!!设置全局标志g的情况:match返回的是一个包含所有匹配项的数组,所以index返回undefined(因为index是索引位置,match匹配了不止一个,所以返回不了具体值,只能返回undefined);exec返回的是每次匹配的项(匹配第一次返回第一次匹配的值cat,第二次返回bat,依次返回)。当有捕获组时,情况不同!match不管捕获组,依然只返回匹配的所有项数组,exec会正常返回其他项是捕获组字符串的数组。

var text="cat, bat, sat, fat";
var pattern=/.at/g;

var matches=text.match(pattern);
var matches1=pattern.exec(text);
console.log(matches);
console.log(matches.index);//0
console.log(matches[0]);//"cat"
       
console.log(matches1);
console.log(matches1.index);
console.log(matches1[0]);

 console.log(pattern.lastIndex);
结果如下:


var text="cat, bat, sat, fat";
var pattern=/.(a)t/g;

var matches=text.match(pattern);
var matches1=pattern.exec(text);
console.log(matches);
console.log(matches.index);//0
console.log(matches[0]);//"cat"
       
console.log(matches1);
console.log(matches1.index);
console.log(matches1[0]);

 console.log(pattern.lastIndex);

结果如下:



大笑有问题有想法欢迎交流,共同进步!

猜你喜欢

转载自blog.csdn.net/qq_27346075/article/details/79861245