本文分享一個以 JavaScript 使用 RegExp 進行正則匹配的實例,示範 exec 方法與相關屬性的用法,供大家參考。
<script type="text/javascript">
var matchedTimes = 0;
// 匹配一個 d,後接一個或多個 b,再接一個 d
// 記住匹配到的 b 與後面的 d,忽略大小寫
var myRe = new RegExp("d(b+)(d)", "ig");
// 等同於 myRe = /d(b+)(d)/ig;
var myArray = myRe.exec("ecDBDsdbbdz");
console.log("Regular Expression String: " + myRe.source);
console.log("Is global? " + myRe.global);
console.log("Ignore case? " + myRe.ignoreCase);
console.log("Is multiline? " + myRe.multiline);
console.log("------------------------------------------------");
logInfo(myArray, myRe);
myArray = myRe.exec("ecDBDsdbbdz");
logInfo(myArray, myRe);
function logInfo(myArray, myRe) {
matchedTimes++;
console.log("This is " + matchedTimes + " times match");
console.log("Original String: " + myArray.input);
console.log("Match Result Array: [" + myArray + "]");
console.log("The 0-based index of the match: " + myArray.index);
console.log("The last matched characters: " + myArray[0]);
console.log("The parenthesized substring matches [1]: " + myArray[1]);
console.log("The parenthesized substring matches [2]: " + myArray[2]);
console.log("The index at which to start the next match: " + myRe.lastIndex);
console.log("-----------------------------------------------");
}
var myRe2 = /^\w+(\d*)$/ig;
console.log("myRe2: " + myRe2.source);
// 因為是 global 匹配,lastIndex 會改變,後續 test 結果會受影響
console.log("myRe2 matches abc? " + myRe2.test("abc"));
</script>這個例子說明了 exec 會回傳包含比對結果的陣列(含比對到的字串、群組與索引等),並透過 lastIndex 記錄下次比對的起點;同時提醒我們,使用 global 標記時 lastIndex 會變動,可能影響後續 test 的結果。