萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 正則表達式 test、exec、match 三大方法深度解析

前言

正則表達式是 JavaScript 處理字符串的利器,而 `test`、`exec`、`match` 是三個最核心的匹配方法。它們雖然都用於模式匹配,但返回值、參數順序、對全局標誌 `g` 的響應行為截然不同。本文通過豐富示例徹底理清三者區別。

一、方法速查表

方法所屬對象參數返回值受 g 影響主要用途
testRegExp字符串Boolean(是否匹配)否(但會更新 lastIndex)快速判斷是否匹配
execRegExp字符串匹配結果數組 / null是(配合 lastIndex 迭代)獲取詳細匹配信息、分組捕獲、迭代所有匹配
matchStringRegExp匹配結果數組 / null是(無 g 返回首個匹配詳情;有 g 返回所有匹配項數組)字符串視角的匹配提取

二、詳細示例與行為差異

1. test —— 簡單的真/假判斷

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 (重置)

2. exec —— 強大的匹配詳情獲取器

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"]

3. match —— 字符串視角的匹配

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"

三、核心差異總結

1. 無捕獲組 + 無 g

`test` 返回 `true`;`exec` 和 `match` 返回相同的詳細數組(含 `index`、`input`)。

2. 無捕獲組 + 有 g

  • `exec`:每次調用返回下一個匹配的詳細數組,需手動循環。
  • `match`:一次性返回所有匹配字符串組成的純數組。

3. 有捕獲組 + 無 g

`exec` 和 `match` 返回相同的詳細數組(第一個元素為完整匹配,後續為捕獲組內容)。

4. 有捕獲組 + 有 g —— 關鍵分水嶺

  • `exec`:仍可迭代,每次返回完整匹配 + 捕獲組詳情。
  • `match`:忽略捕獲組,僅返回所有完整匹配字符串的純數組。

四、最佳實踐建議

  • 只需判斷是否匹配 → reg.test(str)。
  • 需獲取捕獲組、位置信息、或手動控制迭代 → reg.exec(str) 配合 `while` 循環。
  • 需一次性獲取所有匹配字符串(不關心分組) → str.match(regG)。
  • 需獲取所有匹配的詳細信息(含分組、位置) → 必須用 reg.exec(str) 循環,match 無法做到。

五、常見陷阱提醒

  1. 正則對象復用與 lastIndex:帶 `g` 的正則對象是有狀態的,多次調用 `test`/`exec` 會改變 `lastIndex`。在循環或不同字符串間復用時,務必手動重置 `reg.lastIndex = 0`,或每次新建正則對象。
  2. match 不修改正則對象的 `lastIndex`。
  3. exec 返回 `null` 時,`lastIndex` 會自動重置為 0。
copyright © 萬盛學電腦網 all rights reserved