javascript matchAllを使用して正規表現を利用する

javascript matchAllを使用して正規表現を利用する

javascriptで、ES2019で追加されたmatchAllを使用して、正規表現を利用するサンプルコードとなります。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 103.0.5060.134

matchAll使い方

「matchAll」を使用すると、イテレータ形式で扱うことが可能です。

例えば、「e」に一致したものを「正規表現」で確認するには「matchAll」を使用すると、以下のようにイテレーターで返ってきます。

const str = "mebee";
const regexp = /e/g;

for (const match of str.matchAll(regexp)) {
  console.log(match);
}

実行結果

また、以下のように結果を配列としてまとめることも可能です。

const str = "mebee";
const regexp = /e/g;

let result = str.matchAll(regexp);

console.log(Array.from(result));

実行結果

キャプチャグループ

また、どのキャプチャグループにマッチしているのかも、判別しやすくなってます。

const str = "2022-07-07";
const regexp = /(?<year>\d+)-(?<month>\d+)-(?<day>\d+)/g;

let result = str.matchAll(regexp);

console.log(Array.from(result));

実行結果

グローバルフラグ

また、グローバルフラグ「g」をなしで使用するとエラーになるため、グローバルフラグは必須となります。

const str = "2022-07-07";
const regexp = /(?<year>\d+)-(?<month>\d+)-(?<day>\d+)/;

let result = str.matchAll(regexp);

console.log(Array.from(result));
// Uncaught TypeError: String.prototype.matchAll called with a non-global RegExp argument

※参考 「replace」で、グローバルフラグ「g」を使用した場合と、しない場合の違い。

// 先頭のもののみ置換
const str1 = 'mebee'.replace(/e/,'a');

console.log(str1); // mabee

// 全て置換
const str2 = 'mebee'.replace(/e/g,'a');

console.log(str2); // mabaa

サンプルコード

以下は、
「実行」ボタンをクリックすると、フォームに入力した値を、用意した正規表現(eに一致)で一致した値を出力する
サンプルコードとなります。

※cssには「bootstrap5」を使用してます。「bootstrap5」は、IEのサポートを終了してます。関数はアロー関数を利用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css">
</head>

<style>
  .main {
    margin: 0 auto;
    margin-top: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 30px;
  }
</style>
<script>

  const hoge = () => {

    // 正規表現を用意
    const regexp = /e/g;

    // フォームからの値を取得
    const str = foo.value; // document.getElementById('foo');を省略

    // 配列をコピー
    const arr = [...str.matchAll(regexp)];

    // 表示
    disp(arr, "txt");

  }

  //フロントに表示する関数
  const disp = (arr, id) => {
    let text = [];

    // 配列を利用してアロー関数でforEach文を作成
    [...arr].forEach(v => text.push('<li class="list-group-item">' + v + '</li>'))

    //innerHTMLを使用して表示    
    document.getElementById(id).innerHTML = text.join('');
  }

  window.onload = () => {
    // クリックイベントを登録
    btn.onclick = () => { hoge(); }; // document.getElementById('btn');を省略
  }

</script>

<body>
  <div class="main container">

    <h2><span id="result" class="badge bg-info">一致したものを表示</span></h2>
    <ul id="txt" class="list-group list-group-flush"></ul>
    <div class="mb-3">
      <input type="text" id="foo" class="form-control">
    </div>

    <div class="row">
      <button id="btn" type="button" class="btn btn-warning">
        実行
      </button>
    </div>

  </div>

</body>

</html>

用意した正規表現に一致した値が表示されていることが確認できます。