JavaScriptのmatch()で正規表現に一致する文字列を探す

text.match(regex)は文字列を正規表現で検索します。gがなければ最初の一致と詳細、あれば一致した文字列すべてを返します。見つからない場合はnullです。

最初の一致を読み取りnullを扱う

gがないとき、全体の一致は[0]、開始位置はindexです。まずnullを確認するか、結果がなければundefinedを返すfound?.[0]を使います。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="ja">
<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を3つ返します。/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
}

最後の2行はA-17 0 A 17とB-42 5 B 42です。matchAll()に渡すRegExpにはgが必要で、省くとTypeErrorです。配列にするにはArray.from()を使います。String.prototype.matchAll()を参照してください。