核心結論先行
| 場景 | exec 返回 | match 返回 |
| 無捕獲組、無 g | 首個匹配詳情數組 | 首個匹配詳情數組(相同) |
| 無捕獲組、有 g | 每次調用返回下一個匹配詳情 | 所有匹配字符串純數組 |
| 有捕獲組、無 g | 首個匹配詳情(含捕獲組) | 首個匹配詳情(含捕獲組,相同) |
| 有捕獲組、有 g | 每次調用返回詳情(含捕獲組) | 忽略捕獲組,返回所有完整匹配純數組 |
詳細代碼驗證
1. 基礎定義
// 兩種創建方式等價
var reg1 = new RegExp("abc", "g");
var reg2 = /abc/g;
2. 無捕獲組、無 g
var reg = /abc/;
var str = "3abc4,5abc6";
console.log(reg.exec(str)); // ["abc", index: 1, input: "3abc4,5abc6"]
console.log(str.match(reg)); // ["abc", index: 1, input: "3abc4,5abc6"]
3. 無捕獲組、有 g
var reg = /abc/g;
var str = "3abc4,5abc6";
console.log(reg.exec(str)); // ["abc", index: 1, input: "..."]
console.log(reg.exec(str)); // ["abc", index: 6, input: "..."]
console.log(reg.exec(str)); // null
console.log(str.match(reg)); // ["abc", "abc"] <-- 純數組,無 index/input
4. 有捕獲組、無 g
var reg = /a(bc)/;
var str = "3abc4,5abc6";
console.log(reg.exec(str)); // ["abc", "bc", index: 1, input: "..."]
console.log(str.match(reg)); // ["abc", "bc", index: 1, input: "..."]
5. 有捕獲組、有 g —— 關鍵差異
var reg = /a(bc)/g;
var str = "3abc4,5abc6";
console.log(reg.exec(str)); // ["abc", "bc", index: 1, input: "..."]
console.log(reg.exec(str)); // ["abc", "bc", index: 6, input: "..."]
console.log(str.match(reg)); // ["abc", "abc"] <-- 捕獲組 "bc" 丟失!
原理深度解析
exec:正則實例方法,迭代器模式
- 參數是**字符串**。
- 返回匹配詳情數組,含 `index`、`input`、捕獲組。
- 帶 `g` 時,內部維護 `lastIndex`,每次調用從 `lastIndex` 開始搜索,匹配後更新 `lastIndex` 至匹配結束位置。
- 返回 `null` 時自動重置 `lastIndex = 0`。
match:字符串實例方法,一次性提取
- 參數是**正則對象**。
- 無 `g`:行為等同 `exec`(返回首個匹配詳情)。
- 有 `g`:掃描整個字符串,收集所有完整匹配(第 0 組)組成純數組,**完全忽略捕獲組(第 1 組及以後)**,也不返回 `index`/`input`。
- 不修改正則對象的 `lastIndex`。
實戰選型指南
- 需**捕獲組內容**且**全局匹配** → **只能用 `exec` 循環**。
- 只需**所有匹配字符串**,不關心分組、位置 → `str.match(regG)` 最簡潔。
- 需**匹配位置、原字符串引用** → `exec` 或無 `g` 的 `match`。
- 僅判斷**是否匹配** → `reg.test(str)`。
避坑提醒
- 全局正則復用污染:`var reg = /a(bc)/g; str.match(reg); reg.exec(str);` → `exec` 會從上次 `match` 遺留的 `lastIndex` 開始(但 `match` 不改 `lastIndex`,實際不影響)。但多次 `exec` 循環後 `lastIndex` 歸零,後續 `test`/`exec` 正常。最安全:每次新建正則或手動 `reg.lastIndex=0`。
- match 有 g 時返回 null 而非空數組:無匹配時返回 `null`,鏈式調用 `.length` 會報錯,需 `|| []` 兜底。
- 字符串 match 參數若非正則:會隱式 `new RegExp(param)`,特殊字符未轉義會報錯或匹配錯誤,建議顯式構造正則對象。