萬盛學電腦網

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

JavaScript 字串搜尋:match() 方法完整指南與正則應用

前言

match() 方法使用正則表達式搜尋字串,回傳匹配結果陣列或 null。行為取決於正則是否帶有全域旗標 g。本文詳細解析兩種模式差異、回傳結構與實務技巧。

基本語法

str.match(regexp)
  • regexp:正則物件或字串 (隱式轉正則)。
  • 回傳值:見下表兩種模式差異。

兩種模式核心差異

模式正則旗標回傳值用途
非全域無 g陣列:[完整匹配, 捕獲群組1, ...], 含 index, input, groups單次匹配、提取群組
全域有 g陣列:所有完整匹配字串 (無群組資訊);無匹配回傳 null找出所有匹配

實戰範例

範例 1:非全域模式 - 提取群組

const str = 'Hello world!';
const result = str.match(/world/);
console.log(result); 
// ["world", index: 6, input: "Hello world!", groups: undefined]

範例 2:大小寫敏感

console.log(str.match(/World/));   // null
console.log(str.match(/worlld/));  // null
console.log(str.match(/world!/));  // ["world!"]

範例 3:全域模式 - 取得所有匹配

const text = 'apple, Apple, APPLE';
console.log(text.match(/apple/gi)); // ["apple", "Apple", "APPLE"]

範例 4:捕獲群組與全域模式無法共存

const str = '2024-01-15';
console.log(str.match(/(\d{4})-(\d{2})-(\d{2})/)); 
// ["2024-01-15", "2024", "01", "15", index: 0, input: "2024-01-15", groups: undefined]

console.log(str.match(/(\d{4})-(\d{2})-(\d{2})/g)); 
// ["2024-01-15"]  // 群組資訊遺失!

範例 5:matchAll 取得所有匹配含群組 (ES2020)

const str = 'a1b a2c a3d';
const matches = [...str.matchAll(/a(\d)([a-z])/g)];
console.log(matches);
// 每個元素: ["a1b", "1", "b", index: 0, input: "...", groups: undefined]
// 可取得所有匹配的完整群組資訊

進階技巧

1. 判斷是否匹配 (布林值)

const hasNumber = !!str.match(/\d/); // true/false

2. 計算匹配次數

const count = (str.match(/pattern/g) || []).length;

3. 替換配合 matchAll

let result = str;
for (const match of str.matchAll(/pattern/g)) {
  result = result.replace(match[0], replacement);
}

常見誤區

  • 以為 match() 總回傳陣列:無匹配時回傳 null,需用 || [] 防錯。
  • 全域正則重複呼叫問題:同一正則實例帶 g 多次呼叫 match() 會從 lastIndex 繼續,導致結果異常。解決:每次新建正則或重設 lastIndex=0。
  • 混淆 match / search / test:search 回傳索引,test 回傳布林,match 回傳詳細結果。

方法快速選擇指南

需求推薦方法
只需知道是否匹配regex.test(str)
需第一個匹配索引str.search(regex)
需第一個匹配完整資訊(含群組)str.match(regex) // 無 g
需所有匹配字串str.match(regex) // 有 g
需所有匹配含群組資訊[...str.matchAll(regex)] // 有 g
需替換str.replace/replaceAll

總結

match() 是正則提取資料的核心方法。掌握「有無 g 旗標導致完全不同回傳結構」是關鍵。現代專案建議配合 matchAll 處理全域匹配含群組需求,避免手動迴圈與 lastIndex 陷阱。

copyright © 萬盛學電腦網 all rights reserved