正則表達式是 JavaScript 處理字符串的利器,而 `test`、`exec`、`match` 是三個最核心的匹配方法。它們雖然都用於模式匹配,但返回值、參數順序、對全局標誌 `g` 的響應行為截然不同。本文通過豐富示例徹底理清三者區別。
| 方法 | 所屬對象 | 參數 | 返回值 | 受 g 影響 | 主要用途 |
|---|---|---|---|---|---|
test | RegExp | 字符串 | Boolean(是否匹配) | 否(但會更新 lastIndex) | 快速判斷是否匹配 |
exec | RegExp | 字符串 | 匹配結果數組 / null | 是(配合 lastIndex 迭代) | 獲取詳細匹配信息、分組捕獲、迭代所有匹配 |
match | String | RegExp | 匹配結果數組 / null | 是(無 g 返回首個匹配詳情;有 g 返回所有匹配項數組) | 字符串視角的匹配提取 |
var str = "1a1b1c";
var reg = new RegExp("1.", ""); // 無 g 標誌
console.log(reg.test(str)); // true
// 帶 g 標誌時,test 會從 lastIndex 開始查找,並更新 lastIndex
var regG = new RegExp("1.", "g");
console.log(regG.test(str)); // true, lastIndex=2
console.log(regG.test(str)); // true, lastIndex=4
console.log(regG.test(str)); // true, lastIndex=6
console.log(regG.test(str)); // false, lastIndex=0 (重置)
var str = "1a1b1c";
var reg = new RegExp("1.", ""); // 無 g
// 無 g 時,每次調用都返回第一個匹配
console.log(reg.exec(str)); // ["1a", index: 0, input: "1a1b1c", groups: undefined]
console.log(reg.exec(str)); // 同上
// 帶 g 標誌時,可迭代所有匹配
var regG = new RegExp("1.", "g");
console.log(regG.exec(str)); // ["1a", index: 0, ...]
console.log(regG.exec(str)); // ["1b", index: 2, ...]
console.log(regG.exec(str)); // ["1c", index: 4, ...]
console.log(regG.exec(str)); // null (結束,lastIndex 重置為 0)
// 含捕獲組時的返回結構
var regCap = /a(bc)/g;
var str2 = "3abc4,5abc6";
console.log(regCap.exec(str2)); // ["abc", "bc", index: 1, input: "3abc4,5abc6"]
console.log(regCap.exec(str2)); // ["abc", "bc", index: 6, input: "3abc4,5abc6"]
var str = "1a1b1c";
var reg = /1./; // 無 g
// 無 g 時,行為類似 exec(返回首個匹配的詳細數組)
console.log(str.match(reg)); // ["1a", index: 0, input: "1a1b1c"]
// 帶 g 時,返回所有匹配項組成的純數組(不含 index、input 等屬性)
var regG = /1./g;
console.log(str.match(regG)); // ["1a", "1b", "1c"]
// 含捕獲組 + g 時:忽略捕獲組,僅返回完整匹配
var regCapG = /a(bc)/g;
var str2 = "3abc4,5abc6";
console.log(str2.match(regCapG)); // ["abc", "abc"] <-- 注意:不返回 "bc"
`test` 返回 `true`;`exec` 和 `match` 返回相同的詳細數組(含 `index`、`input`)。
`exec` 和 `match` 返回相同的詳細數組(第一個元素為完整匹配,後續為捕獲組內容)。
reg.test(str)。reg.exec(str) 配合 `while` 循環。str.match(regG)。reg.exec(str) 循環,match 無法做到。match 不修改正則對象的 `lastIndex`。exec 返回 `null` 時,`lastIndex` 會自動重置為 0。