正則表達(dá)式中字符串模式匹配方法exec和match的區(qū)別
js正則表達(dá)式中字符串模式匹配方法exec()和match()的有相近的作用,但也存在一些需要注意的區(qū)別泊业。
第一點(diǎn)0∫住!篮奄!
這是沒有設(shè)置全局標(biāo)志g的情況:exec專門為捕獲組而設(shè)計(jì)割去,可接受一個(gè)參數(shù),即要應(yīng)用模式的字符串劫拗,然后返回一個(gè)數(shù)組(沒有捕獲組時(shí)矾克,數(shù)組只包含一項(xiàng)胁附,即第一個(gè)匹配項(xiàng)信息;有捕獲組時(shí)控妻,其他項(xiàng)是模式中的捕獲組匹配的字符串)。match也只接受一個(gè)參數(shù)郎哭,即一個(gè)正則表達(dá)式或regExp對(duì)象,返回的是一個(gè)數(shù)組邦蜜,與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)
結(jié)果如下:
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);
結(jié)果如下:
第二點(diǎn)=惆纭!茶敏!
設(shè)置全局標(biāo)志g的情況:match返回的是一個(gè)包含所有匹配項(xiàng)的數(shù)組睡榆,所以index返回undefined(因?yàn)閕ndex是索引位置,match匹配了不止一個(gè)胀屿,所以返回不了具體值,只能返回undefined)亲铡;exec返回的是每次匹配的項(xiàng)(匹配第一次返回第一次匹配的值cat葡兑,第二次返回bat,依次返回)讹堤。當(dāng)有捕獲組時(shí),情況不同疑务!match不管捕獲組梗醇,依然只返回匹配的所有項(xiàng)數(shù)組,exec會(huì)正常返回其他項(xiàng)是捕獲組字符串的數(shù)組温鸽。
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);
結(jié)果如下:
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);
結(jié)果如下: