match() 方法使用正則表達式搜尋字串,回傳匹配結果陣列或 null。行為取決於正則是否帶有全域旗標 g。本文詳細解析兩種模式差異、回傳結構與實務技巧。
str.match(regexp)
| 模式 | 正則旗標 | 回傳值 | 用途 |
|---|---|---|---|
| 非全域 | 無 g | 陣列:[完整匹配, 捕獲群組1, ...], 含 index, input, groups | 單次匹配、提取群組 |
| 全域 | 有 g | 陣列:所有完整匹配字串 (無群組資訊);無匹配回傳 null | 找出所有匹配 |
const str = 'Hello world!';
const result = str.match(/world/);
console.log(result);
// ["world", index: 6, input: "Hello world!", groups: undefined]
console.log(str.match(/World/)); // null
console.log(str.match(/worlld/)); // null
console.log(str.match(/world!/)); // ["world!"]
const text = 'apple, Apple, APPLE';
console.log(text.match(/apple/gi)); // ["apple", "Apple", "APPLE"]
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"] // 群組資訊遺失!
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]
// 可取得所有匹配的完整群組資訊
const hasNumber = !!str.match(/\d/); // true/false
const count = (str.match(/pattern/g) || []).length;
let result = str;
for (const match of str.matchAll(/pattern/g)) {
result = result.replace(match[0], replacement);
}
null,需用 || [] 防錯。g 多次呼叫 match() 會從 lastIndex 繼續,導致結果異常。解決:每次新建正則或重設 lastIndex=0。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 陷阱。