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)
複製代碼
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]
複製代碼
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']
複製代碼
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']
複製代碼
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的理解正則表達式