コンテンツへスキップ
uencoder

Regular Expression

正規表現は文字列パターンを記述する形式言語であり、メタ文字と量指定子でマッチング規則を定義する。検索・検証・抽出に広く使われる。

目的

手書きのパース処理を置き換える、簡潔かつ強力な文字列パターンマッチング言語を提供する。

メカニズム

リテラル文字とメタ文字(. * + ? [] () {} \ | ^ $)で構成される。量指定子が繰り返しを制御する(* は 0 回以上、+ は 1 回以上、? は 0 回か 1 回、{n,m} は指定範囲)。グループ化 () はキャプチャ、| は選択、[] は文字クラス、\d \w \s は定義済みクラスである。エンジンは NFA/DFA のバックトラッキングまたはオートマトンでマッチする。

ユースケース

  • フォーム入力の検証(メール、電話番号)
  • ログからのパターン抽出
  • 検索と置換(IDE や sed)
  • レキサーの生成

例

  • 入力
    /\d{3}-\d{4}/
    Output
    Matches 123-4567

    3 digits-4 digits

よくあるエラー

The greedy quantifier .* matches too much
Use the non-greedy .*? or a precise character class

関連用語

関連ツール

References