正則表達式是 JavaScript 處理「字串比對、擷取、驗證」的核心工具。本文把 RegExp 對象最常被用到的 API 做了一次系統性梳理,從最簡單的 test() 一路談到 exec()、靜態屬性與實例屬性,適合當作日常查閱的小抄。
test() 接受一個字串,回傳布爾值,用來判斷該字串中是否存在符合模式的片段。它是所有方法裡最輕量、最單純的一個。
var text = "cat, bat, sat, fat";
var pattern = /.at/;
if (pattern.test(text)) {
console.log("The pattern was matched.");
}
點號「.」代表任意單一字元,因此 /.at/ 會命中 cat、bat、sat、fat 這四個片段。只要有一處符合,test() 就回傳 true。
把 RegExp 實例轉成字串時,輸出的就是「斜線 + 主體 + 修飾符」這種字面量形式,方便除錯時直接貼回程式碼裡使用。
var pattern = new RegExp("\\[bc\\]at", "gi");
console.log(pattern.toString()); // /\[bc\]at/gi
console.log(pattern.toLocaleString()); // /\[bc\]at/gi
這裡有個容易踩到的細節:用 new RegExp 從字串建構表達式時,反斜線本身也需要跳脫,所以要寫 \\ 才會得到一個真正的 \;而使用字面量語法時,寫 \ 即可。
除了實例本身,RegExp 構造函數上也掛了一組「最近一次比對結果」的資訊屬性。它們同時具有長屬性名與短屬性名兩套寫法。
var text = "this has been a short summer";
var pattern = /(.)hort/g;
if (pattern.test(text)) {
console.log(RegExp.input); // this has been a short summer
console.log(RegExp.leftContext); // this has been a
console.log(RegExp.rightContext); // summer
console.log(RegExp.lastMatch); // short
console.log(RegExp.lastParen); // s
console.log(RegExp.multiline); // false
}
對應關係整理如下:
短寫法在實務上較少用,一方面是可讀性差,另一方面各家瀏覽器的支援程度不一(例如部分版本 Opera 不支援短屬性名,IE 則不支援 multiline)。閱讀舊程式碼時認得即可,自己撰寫時建議優先用長屬性名。
var text = "this has been a short summer";
var pattern = /(..)or(.)/g;
if (pattern.test(text)) {
console.log(RegExp.$1); // sh
console.log(RegExp.$2); // t
}
每當產生一次帶括號的成功匹配,$1~$9 就會被更新。雖然一個模式中可以寫入任意多組括號,但這些屬性最多只會保留最新的九組,這也是它們實用性受限的原因——在需要多組捕獲時,改用 exec() 或 match() 會可靠得多。
test() 只回答「有沒有」,exec() 則回答「在哪裡、是什麼、各組內容為何」。它回傳一個類似陣列的結果物件,包含 index、input 以及各個捕獲組。
var text = "mom and dad and baby";
var pattern = /mom( and dad( and baby)?)?/gi;
var matches = pattern.exec(text);
console.log(matches.index); // 0 整體匹配的起始位置
console.log(matches.input); // "mom and dad and baby" 原始字串
console.log(matches[0]); // "mom and dad and baby" 完整匹配
console.log(matches[1]); // " and dad and baby" 第一個捕獲組
console.log(matches[2]); // " and baby" 第二個捕獲組
而 lastIndex 的行為,取決於正則是否帶 g 修飾符:
var text = "cat, bat, sat, fat";
var p1 = /.at/;
var m1 = p1.exec(text);
console.log(m1.index, m1[0], p1.lastIndex); // 0 "cat" 0
var p2 = /.at/g;
var m2 = p2.exec(text);
console.log(m2.index, m2[0], p2.lastIndex); // 0 "cat" 3
m2 = p2.exec(text);
console.log(m2.index, m2[0], p2.lastIndex); // 5 "bat" 8
沒有 g 的表達式每次都從頭找起,lastIndex 恆為 0;帶 g 的表達式則會記住上次結束的位置繼續往後掃,一旦匹配失敗,lastIndex 會自動歸零。理解了這點,就能解釋為什麼「用迴圈搭配 exec() 遍歷所有結果」是可行的,而 test() 卻不行。
var pattern1 = /\[bc\]at/i;
console.log(pattern1.global); // false 是否全域搜尋
console.log(pattern1.ignoreCase); // true 是否忽略大小寫
console.log(pattern1.multiline); // false 是否多行比對
console.log(pattern1.lastIndex); // 0 下次比對的起始位置
console.log(pattern1.source); // "\[bc\]at" 表達式的源文字
var pattern2 = new RegExp("\\[bc\\]at", "i");
console.log(pattern2.global, pattern2.ignoreCase, pattern2.multiline, pattern2.source);
// false true false "\[bc\]at"
字面量語法與 new RegExp 建構出來的物件,在屬性上完全等價。兩者的選擇標準很實際:模式固定寫死就用字面量,需要動態組字(例如把使用者輸入或迴圈變數拼進模式)時才用 new RegExp。
以上就是本次的 JavaScript 學習小結。RegExp 的 API 看似零碎,但只要抓住「test 判斷、exec 取值、lastIndex 記位置」這三條主線,日常開發中的絕大多數場景都能應付。