正規表現: パターンマッチング
文字列の検索・置換・抽出。バリデーションに必須。
RegExp
正規表現オブジェクト。
test
マッチするか真偽値で返す。
match
マッチした部分を配列で取得。
正規表現基礎
メールアドレスのチェック、電話番号の抽出、URLの書き換えなど、複雑な文字列操作を一瞬で片付けます。最初は暗号に見えますが、基本的な記号(`^`, `$`, `d`, `+`)を覚えるだけで魔法のように便利になります。
// 正規表現リテラル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); // 高速}パターン
// よく使うパターン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 フラグを使い分けてください。