potisanのプログラミングメモ

趣味のプログラマーがプログラミング関係で気になったことや調べたことをいつでも忘れられるようにメモするブログです。はてなブログ無料版なので記事の上の方はたぶん広告です。記事中にも広告挿入されるみたいです。

JavaScript 文字列の正規表現マッチ結果をクラスで保持する

JavaScriptで文字列の正規表現のマッチ結果をクラスで保持するサンプルコードです。正規表現のマッチ結果に限らず、文字列の処理結果を保持する方法の骨組みとして使えます。

正規表現を適用した文字列を保持する必要がある場合は前者「クラスで正規表現のマッチ結果だけ保持する場合」、保持する必要がない場合や整形したデータを多用する場合は後者「クラスで正規表現のマッチ結果を整形して保持する場合」を推奨します。

クラスで正規表現のマッチ結果だけ保持する場合

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>Sample</title>
<script>
class SampleClass {
  #match;
  constructor(s) {
    this.#match = s.match(/^(?<sex>M|F)-(?<id>\d+)_(?<name>.+)\.jpg$/ui);
  }
  get input() { return this.#match.input; }
  get sex() { return this.#match.groups.sex; }
  get id() { return this.#match.groups.id; }
  get name() { return this.#match.groups.name; }

  static parseStrings(strings) {
    return Array.from(strings, s => new SampleClass(s));
  }
}

const inputs = ["M-123_taro\.jpg", "m-124_jiro\.jpg", "F-456_hanako\.jpg"];
const samples = SampleClass.parseStrings(inputs);
</script>
</head>
<body>
<script>
samples.forEach(sample =>
  document.writeln(`<p>${sample.sex},${sample.id},${sample.name}</p>`));
// M,123,taro
// m,124,jiro
// F,456,hanako
</script>
</body>
</html>

クラスで正規表現のマッチ結果を整形して保持する場合

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>Sample</title>
<script>
class SampleClass {
  #sex;
  #id;
  #name;
  constructor(s) {
    const m = s.match(/^(?<sex>M|F)-(?<id>\d+)_(?<name>.+)\.jpg$/ui);
    this.#sex  = m.groups.sex.toUpperCase();
    this.#id   = parseInt(m.groups.id);
    this.#name = m.groups.name;
  }
  get sex() { return this.#sex; }
  get id() { return this.#id; }
  get name() { return this.#name; }

  static parseStrings(strings) {
    return Array.from(strings, s => new SampleClass(s));
  }
}

const inputs = ["M-123_taro\.jpg", "m-124_jiro\.jpg", "F-456_hanako\.jpg"];
const samples = SampleClass.parseStrings(inputs);
</script>
</head>
<body>
<script>
samples.forEach(sample =>
  document.writeln(`<p>${sample.sex},${sample.id},${sample.name}</p>`));
// M,123,taro
// m,124,jiro
// F,456,hanako
</script>
</body>
</html>

参考