萬盛學電腦網

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

JavaScript String.prototype.match() 完整指南:正則匹配擷取

前言

match() 方法依正則表達式檢索字串,行為隨 g (global) 旗標而異。是字串解析、資料擷取、格式驗證的核心工具。

語法

str.match(regexp)

兩種模式差異

模式旗標回傳值
非全域無 g同 RegExp.exec():[match, group1, ..., index, input, groups] 或 null
全域有 g所有匹配字串組成的陣列 [match1, match2, ...],無匹配回傳 null

非全域模式範例(含捕獲群組)

<script>
const str = 'Chapter 3.4.5.1';
const re = /(chapter\s+\d+(\.\d+)*)/i;
const result = str.match(re);

console.log(result[0]);    // 'Chapter 3.4.5.1' (完整匹配)
console.log(result[1]);    // 'Chapter 3.4.5.1' (第1群組)
console.log(result[2]);    // '.1' (第2群組)
console.log(result.index); // 0
console.log(result.input); // 原字串
</script>

全域模式範例

<script>
const str = 'A1 B2 C3 D4';
const re = /\d/g;
console.log(str.match(re)); // ['1', '2', '3', '4']

// 注意:全域模式下不提供群組資訊與索引
// 需群組資訊請使用 matchAll() (ES2020)
for (const match of str.matchAll(/([A-Z])(\d)/g)) {
  console.log(match[0], match[1], match[2]); // A1 A 1, B2 B 2...
}
</script>

常見陷阱

  • 傳入非 RegExp 會隱式轉換:str.match('abc') 等同 str.match(/abc/)。
  • 全域 RegExp 的 lastIndex 會保留狀態,重複呼叫需手動歸零或改用 matchAll()。

現代替代:matchAll()

const matches = [...str.matchAll(/(\w+)@(\w+)\.(\w+)/g)];
// 每個 match 為完整結果陣列,含群組、索引、groups

總結

理解 match() 兩種模式差異至關重要。需群組資訊且全域搜尋時,請改用 matchAll() 獲得完整、可迭代的結果。

copyright © 萬盛學電腦網 all rights reserved