≪ Today I learned. RSS購読
公開日
タグ
JavaScript
著者
ダーシノ(@bc_rikko)

名前付きキャプチャグループでString#match()をより使いやすく

ある文字列から正規表現でマッチした部分を抽出する際、String#match()を使う。普通に使うと以下のようにmatch[n]という非常にわかりづらいコードになる。

const str = "2025-03-27 タイトル @username";

const match = str.match(/(\d{4}-\d{2}-\d{2})\s(.+)\s@(.+)/);
if (match) {
  console.log(
    'date:', match[1],
    'title:', match[2],
    'username:', match[3]
  );
}

分割代入(Destructuring)を使うことで、ちょっとはわかりやすくなるが、それ以上に名前付きキャプチャグループが使いやすい。

(?<name>pattern)
const str = "2025-03-27 タイトル @username";

const groups = str.match(/(?<date>\d{4}-\d{2}-\d{2})\s(?<title>.+)\s@(?<username>.+)/)?.groups;

if (groups) {
  console.log(
    'date:', groups.date,
    'title:', groups.title,
    'username:', groups.username
  );
}

ただし、TypeScriptで使う場合はString#match().groupsの型がRecord<string, string>となるため、型アサーションがあると便利だろう。