字串的match方法與正則的exec方法的區別

eagle發表於2018-12-20
  1. match是字串的方法,exec是正則物件例項的方法
  2. 正規表示式中沒有子表示式,且非全域性匹配(沒有修飾符g),match和exec結果一樣都是返回陣列
var s ='hello123456陣列';
var result1 = s.match(/\d/);
console.log(result1);//["1", index: 5, input: "hello123456陣列", groups: undefined]

var result2 = /\d/.exec(s);
console.log(result2);//結果同string.match(reg) 
複製程式碼
  1. 正規表示式中含有子表示式,且非全域性匹配,match和exec結果一致
var s='abc,bbc,cbc,dbc';
var result=/(\w)bc/.exec(s);
console.log(result);

var result2=s.match(/(\w)bc/);
console.log(result2);
//["abc", "a", index: 0, input: "abc,bbc,cbc,dbc", groups: undefined],返回長度為2的陣列,第一項時匹配項,第二項是子表示式捕獲項,包含屬性,index和input,index是匹配項開始的下標


var str = 'abcd';
var re = /(a)(b)(c)/;
console.log( str.match(re) ) //["abc", "a", "b", "c", index: 0, input: "abcd", groups: undefined]
console.log(re.exec(str));//["abc", "a", "b", "c", index: 0, input: "abcd", groups: undefined]

複製程式碼
  1. 正規表示式中沒有子表示式,全域性匹配。match返回所有匹配項組成的陣列,exec返回一個匹配項的陣列
var s = 'abc,bbc,cbc,dbc';
var result = /\wbc/g.exec(s);
console.log(result); //["abc", index: 0, input: "abc,bbc,cbc,dbc", groups: undefined]
var result2 = s.match(/\wbc/g);
console.log(result2); //['abc','bbc','cbc','dbc']
複製程式碼
  1. 正規表示式中有子表示式,全域性匹配。match返回所有匹配項組成的陣列,忽略子表示式的捕獲項,exec忽略全域性匹配。
var s = 'abc,bbc,cbc,dbc';
var result = /(\w)bc/g.exec(s);
console.log(result); //['abc','a'],index為0,input為'abc,bbc,cbc,dbc'
var result2 = s.match(/(\w)bc/g);
console.log(result2); //['abc','bbc','cbc','dbc']
複製程式碼
  1. exec適合用於迴圈匹配,雖然全域性匹配和非全域性的返回值一樣,但使用exec迴圈時,必須要加修飾符g
var s = 'abc,bbc,cbc,dbc';
var reg = /(\w)bc/g;
var resultArr = [];
//迴圈匹配時,要先將正規表示式定義好,不然每次都是一個新的正則物件,影響lastIndex的變化 
//一定要加修飾符g,lastIndex是匹配項後面的下標,是下一次匹配的開始下標 
//當 exec() 再也找不到匹配的文字時,它將返回 null,並把lastIndex 屬性重置為 0
while (result = reg.exec(s)) {
    console.log("lastIndex: " + reg.lastIndex);
    // lastIndex: 3 
    // lastIndex: 7 
    // lastIndex: 11 
    // lastIndex: 15
    resultArr.push(result);
}
console.log(resultArr)
// [Array(2), Array(2), Array(2), Array(2)]
// ["abc", "a", index: 0, input: "abc,bbc,cbc,dbc", groups: undefined]
// ["bbc", "b", index: 4, input: "abc,bbc,cbc,dbc", groups: undefined]
// ["cbc", "c", index: 8, input: "abc,bbc,cbc,dbc", groups: undefined]
// ["dbc", "d", index: 12, input: "abc,bbc,cbc,dbc", groups: undefined]

複製程式碼

參考資料:1. lastIndex的理解

相關文章