javascriptRegex修飾符之global(/g)的使用,Regexglobal
/g修飾符代表全域匹配,尋找所有匹配而非在找到第一個匹配後停止。先看一段經典代碼:
var str = "123#abc";var noglobal = /abc/i;//非全域匹配模式console.log(re.test(str)); //輸出tureconsole.log(re.test(str)); //輸出tureconsole.log(re.test(str)); //輸出tureconsole.log(re.test(str)); //輸出turevar re = /abc/ig;//全域匹配console.log(re.test(str)); //輸出tureconsole.log(re.test(str)); //輸出falseconsole.log(re.test(str)); //輸出tureconsole.log(re.test(str)); //輸出false
可以看到:當使用/g模式的時候,多次執行RegExp.test()的輸出結果會有差別。下面的解釋摘抄自這篇部落格:
在建立Regex對象時如果使用了“g”標識符或者設定它了的?global屬性值為ture時,那麼新建立的Regex對象將使用模式對要將要匹配的字串進行全域匹配。在全域匹配模式下可以對指定要尋找的字串執行多次匹配。每次匹配使用當前正則對象的lastIndex屬性的值作為在目標字串中開 始尋找的起始位置。lastIndex屬性的初始值為0,找到匹配的項後lastIndex的值被重設為匹配內容的下一個字元在字串中的位置索引,用來標識下次執行匹配時開始尋找的位置。如果找不到匹配的項lastIndex的值會被設定為0。當沒有設定正則對象的全域匹配標誌時lastIndex屬性的值始終為0,每次執行匹配僅尋找字串中第一個匹配的項。
可以通過下面這段代碼驗證lastIndex在/g模式下的表現:
var str = "012345678901234567890123456789"; var re = /123/g; console.log(re.lastIndex); //輸出0,Regex剛開始建立console.log(re.test(str)); //輸出ture console.log(re.lastIndex); //輸出4 console.log(re.test(str)); //輸出true console.log(re.lastIndex); //輸出14 console.log(re.test(str)); //輸出ture console.log(re.lastIndex); //輸出24 console.log(re.test(str)); //輸出false console.log(re.lastIndex); //輸出0,沒有找到匹配項被重設
上面我們看到了/g模式對於RegExp.test()函數的影響,現在我們看下對RegExp.exec()函數的影響。RegExp.exec()返回一個數組,其中存放匹配的結果。如果未找到匹配,則返回值為 null。
var str = "012345678901234567890123456789"; var re = /abc/; //exec沒有找到匹配console.log(re.exec(str));//nullconsole.log(re.lastIndex);//0
var str = "012345678901234567890123456789"; var re = /123/; var resultArray = re.exec(str);console.log(resultArray[0]);//匹配結果123console.log(resultArray.input);//目標字串strconsole.log(resultArray.index);//匹配結果在原始字串str中的索引
對於RegExp.exec方法,不加入g,則只返回第一個匹配,無論執行多少次均是如此;如果加入g,則第一次執行也返回第一個匹配,再執行返回第二個匹配,依次類推。
var str = "012345678901234567890123456789"; var re = /123/; var globalre = /123/g;//非全域匹配var resultArray = re.exec(str);console.log(resultArray[0]);//輸出123console.log(resultArray.index);//輸出1console.log(globalre.lastIndex);//輸出0var resultArray = re.exec(str);console.log(resultArray[0]);//輸出123console.log(resultArray.index);//輸出1console.log(globalre.lastIndex);//輸出0//全域匹配var resultArray = globalre.exec(str);console.log(resultArray[0]);//輸出123console.log(resultArray.index);//輸出1console.log(globalre.lastIndex);//輸出4var resultArray = globalre.exec(str);console.log(resultArray[0]);//輸出123console.log(resultArray.index);//輸出11console.log(globalre.lastIndex);//輸出14
當使用/g匹配模式的時候,我們可以通過迴圈,擷取所有的匹配項。
var str = "012345678901234567890123456789"; var globalre = /123/g;//迴圈遍曆,擷取所有匹配var result = null;while ((result = globalre.exec(str)) != null){console.log(result[0]);console.log(globalre.lastIndex);}