文字列のパターンマッチング・抽出・置換に使う
// ── 正規表現の書き方 /パターン/フラグ ────────────────────
// または new RegExp('パターン', 'フラグ') でも作れる
// ── test: パターンに一致するか判定 ─────────────────────
const emailPattern = /^[^s@]+@[^s@]+.[^s@]+$/;
console.log(emailPattern.test('[email protected]')); // true
console.log(emailPattern.test('invalid-email')); // false
const phonePattern = /^0d{1,4}-d{1,4}-d{4}$/; // 日本の電話番号
console.log(phonePattern.test('090-1234-5678')); // true
console.log(phonePattern.test('12345')); // false
// ── replace: パターンにマッチした部分を置換 ──────────
// g フラグ = 全マッチを置換
const str = ' hello world ';
const clean = str.replace(/s+/g, ' ').trim(); // 'hello world'
// ── match: マッチした部分を取得 ──────────────────────
const text = '価格は 1000 円と 2500 円です';
const numbers = text.match(/d+/g); // ['1000', '2500']
// ── よく使うパターン ─────────────────────────────────
// 数字のみ: /^d+$/
// 英数字のみ: /^[a-zA-Z0-9]+$/
// 郵便番号: /^\d{3}-\d{4}$/
名前付きキャプチャグループ(?<n>)を使うとm[1]より可読性が高い。フラグ: g=全件, i=大小無視, m=複数行, s=.が改行にマッチ。