用 JavaScript 的 match() 查找正则表达式匹配

text.match(regex) 用正则表达式查找字符串。没有 g 时返回首个匹配及其详情,有 g 时返回所有匹配文本。找不到时,两者都返回 null。

读取首个匹配并处理 null

没有 g 时,[0] 是完整匹配,index 是起始索引。先检查 null,或者使用 found?.[0] 在结果缺失时得到 undefined。请参阅 String.prototype.match()。

const text = 'Lorem Ipsum Dolor';
const found = text.match(/Lo/);
console.log(found[0]);     // 'Lo'
console.log(found.index);  // 0

const absent = text.match(/Loi/);
console.log(absent);       // null
console.log(absent?.[0]);  // undefined

结合 g、i 和捕获组

在此示例中,i 忽略大小写。没有 g 时,从 [1] 起可以读取捕获组。有 g 则不包含各匹配的索引和捕获。此处的 \w 能匹配 Lo 后的英文字母,但不能覆盖所有 Unicode 字母。

const text = 'Lorem Ipsum Dolor';
console.log(text.match(/lo/i)[0]);    // 'Lo'
console.log(text.match(/o/g));        // ['o', 'o', 'o']

const captured = text.match(/Lo(\w+)/);
console.log(captured[0]); // 'Lorem'
console.log(captured[1]); // 'rem'
console.log(captured.index); // 0

运行完整的 match() 示例

将完整代码以 UTF-8 保存为 match-example.html 并打开。菜单使用预设模式,便于比较标志和捕获,无需每次编写新表达式。

<!doctype html>
<html lang="zh">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>比较 String.match 的结果</title>
</head>
<body>
<label for="source">要查找的文本</label>
<input id="source" type="text" value="Lorem Ipsum Dolor">
<label for="pattern">正则表达式</label>
<select id="pattern">
  <option value="first">/Lo/ 首个匹配</option>
  <option value="insensitive">/lo/i 忽略大小写</option>
  <option value="all">/o/g 所有匹配</option>
  <option value="capture">/Lo(\w+)/ 捕获</option>
  <option value="missing">/Loi/ 没有匹配</option>
</select>
<button id="search" type="button">查找</button>
<button id="reset" type="button">重置</button>
<pre id="output" aria-live="polite"></pre>
<script>
const patterns = {
  first: /Lo/,
  insensitive: /lo/i,
  all: /o/g,
  capture: /Lo(\w+)/,
  missing: /Loi/
};
const source = document.querySelector('#source');
const choice = document.querySelector('#pattern');
const output = document.querySelector('#output');

function show() {
  const regex = patterns[choice.value];
  const result = source.value.match(regex);
  if (result === null) {
    output.textContent = '没有匹配:null';
  } else if (regex.global) {
    output.textContent = `匹配文本: ${JSON.stringify(result)}`;
  } else {
    const captured = result.length > 1 ? result.slice(1).join(', ') : '无';
    output.textContent = `首个匹配: ${result[0]}\n起始索引: ${result.index}\n捕获: ${captured}`;
  }
}

document.querySelector('#search').addEventListener('click', show);
document.querySelector('#reset').addEventListener('click', () => {
  source.value = 'Lorem Ipsum Dolor';
  choice.value = 'first';
  show();
});
show();
</script>
</body>
</html>

初始结果是位置 0 的 Lo。/o/g 返回三个 o。/Lo(\w+)/ 返回 Lorem 和捕获 rem。/Loi/ 返回 null。更改文本后可以重置为初始输入和选项。

选择 match()、matchAll() 或简单检查

反复检查是否匹配时可使用不带 g和y 的 test()。要定位固定文本,可使用 indexOf()。需要每处匹配的详情时,用 matchAll()。

两个命名组分别捕获字母和数字。全局 match() 返回匹配文本。遍历 matchAll() 的结果,还能读取每处的起始索引和两个捕获组。

{
  const text = 'A-17 B-42';
  const pattern = /(?<code>[A-Z])-(?<number>\d+)/g;

  console.log(text.match(pattern)); // ['A-17', 'B-42']

  for (const match of text.matchAll(pattern)) {
    console.log(match[0], match.index, match.groups.code, match.groups.number);
  }
  // A-17 0 A 17
  // B-42 5 B 42
}

最后两行是 A-17 0 A 17 和 B-42 5 B 42。向 matchAll() 传入 RegExp 时必须带 g,否则会抛出 TypeError。需要数组时可使用 Array.from()。请参阅 String.prototype.matchAll()。