正規表現: パターンマッチング

文字列の検索・置換・抽出。バリデーションに必須。

RegExp
正規表現オブジェクト。
test
マッチするか真偽値で返す。
match
マッチした部分を配列で取得。

正規表現基礎

超強力な検索フィルター (Super Search Filter)

正規表現は「超強力な検索フィルター」です。普通の検索は「"apple"」という単語しか探せませんが、正規表現なら「"a"で始まって、数字を含み、最後に"e"で終わる単語」のように、複雑な「パターン(型)」で検索できます。

メールアドレスのチェック、電話番号の抽出、URLの書き換えなど、複雑な文字列操作を一瞬で片付けます。最初は暗号に見えますが、基本的な記号(`^`, `$`, `d`, `+`)を覚えるだけで魔法のように便利になります。

test, match, replace
// 正規表現リテラル
const pattern = /hello/i; // i = 大文字小文字無視
// test: マッチするか
pattern.test('Hello World'); // true
// match: マッチを取得
'abc123def'.match(/\d+/); // ['123']
// replace: 置換
'hello world'.replace(/world/, 'JS'); // 'hello JS'
// exec: キャプチャグループ
const result = /(\w+)@(\w+)/.exec('alice@example');
// ['alice@example', 'alice', 'example']
Bad
// ❌ Bad: 毎回コンパイル
for (const s of strings) {
s.match(new RegExp(pattern)); // 遅い
}
Good
// ✅ Good: リテラルで一度だけ
const re = /pattern/g;
for (const s of strings) {
s.match(re); // 高速
}

パターン

Email, Named Groups
// よく使うパターン
const email = /^[\w.-]+@[\w.-]+\.\w+$/;
const phone = /^\d{3}-\d{4}-\d{4}$/;
const url = /^https?:\/\/[\w.-]+/;
// フラグ
// g: グローバル(全てマッチ)
// i: 大文字小文字無視
// m: 複数行
// s: . が改行にもマッチ
// u: Unicode
// 名前付きキャプチャ (ES2018)
const dateRe = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const { groups } = dateRe.exec('2024-01-15');
// groups.year = '2024'
// replaceAll (ES2021)
'a-b-c'.replaceAll('-', '_'); // 'a_b_c'
Tip: 名前付きキャプチャで可読性向上。

合格ライン

test と match を使える
フラグ (g, i) を使い分けられる

演習課題

課題1: test と match
test と match でパターンマッチングしてください。
課題2: フラグ
g と i フラグを使い分けてください。