Use Cases

Claude Codeで正規表現を作成・デバッグする方法

Claude Codeを使って複雑な正規表現を簡単に作成・テスト・デバッグする実践テクニック。具体的なプロンプト例と動くコードで解説。

正規表現の悩みをClaude Codeで解決する

正規表現は強力なツールですが、複雑なパターンになると読み書きが難しく、デバッグにも時間がかかります。Claude Codeを使えば、自然言語で要件を伝えるだけで正確な正規表現を生成し、テストコードまで一括で作成できます。

基本的な使い方に慣れていない方は、まずClaude Codeの入門ガイドをご覧ください。

基本:自然言語から正規表現を生成する

プロジェクトディレクトリで次のようにプロンプトを入力します。

> 日本の電話番号(ハイフンあり・なし両対応)にマッチする正規表現をTypeScriptで作って。テストコードも書いて。

Claude Codeが生成するコード例:

const phoneRegex = /^0[0-9]{1,4}[-]?[0-9]{1,4}[-]?[0-9]{3,4}$/;

// 携帯電話番号の厳密なパターン
const mobileRegex = /^0[789]0[-]?\d{4}[-]?\d{4}$/;

function validatePhone(input: string): boolean {
  return phoneRegex.test(input) || mobileRegex.test(input);
}

// テスト
const testCases = [
  { input: "090-1234-5678", expected: true },
  { input: "09012345678", expected: true },
  { input: "03-1234-5678", expected: true },
  { input: "0312345678", expected: true },
  { input: "123-4567-8901", expected: false },
  { input: "abc-defg-hijk", expected: false },
];

testCases.forEach(({ input, expected }) => {
  const result = validatePhone(input);
  console.assert(
    result === expected,
    `Failed: ${input} => ${result}, expected ${expected}`
  );
});

console.log("All tests passed!");

既存の正規表現をデバッグする

プロジェクト内の正規表現がうまく動かないとき、Claude Codeに直接聞けます。

> src/utils/validator.ts の emailRegex が[email protected]にマッチしない原因を調べて修正して

Claude Codeはファイルを読み取り、正規表現の問題箇所を特定して修正します。例えば + 記号のエスケープ漏れなど、見落としやすいバグを即座に発見できます。

実践パターン:URLパーサーの構築

Webスクレイピングやログ解析で役立つURLパーサーの例です。

interface ParsedUrl {
  protocol: string;
  host: string;
  port?: string;
  path: string;
  query?: Record<string, string>;
  fragment?: string;
}

function parseUrl(url: string): ParsedUrl | null {
  const regex =
    /^(https?):\/\/([^:/?#]+)(?::(\d+))?(\/[^?#]*)?(?:\?([^#]*))?(?:#(.*))?$/;
  const match = url.match(regex);

  if (!match) return null;

  const queryParams: Record<string, string> = {};
  if (match[5]) {
    match[5].split("&").forEach((pair) => {
      const [key, value] = pair.split("=");
      queryParams[decodeURIComponent(key)] = decodeURIComponent(value || "");
    });
  }

  return {
    protocol: match[1],
    host: match[2],
    port: match[3],
    path: match[4] || "/",
    query: match[5] ? queryParams : undefined,
    fragment: match[6],
  };
}

// 使用例
const result = parseUrl("https://example.com:8080/api/users?page=1&limit=10#section");
console.log(result);
// {
//   protocol: "https",
//   host: "example.com",
//   port: "8080",
//   path: "/api/users",
//   query: { page: "1", limit: "10" },
//   fragment: "section"
// }

正規表現の可読性を上げるテクニック

Claude Codeに「名前付きキャプチャグループを使って」と指示すると、可読性の高い正規表現を生成します。

// 日付パーサー(名前付きキャプチャグループ使用)
const dateRegex =
  /^(?<year>\d{4})[-\/](?<month>0[1-9]|1[0-2])[-\/](?<day>0[1-9]|[12]\d|3[01])$/;

function parseDate(input: string) {
  const match = input.match(dateRegex);
  if (!match?.groups) return null;

  return {
    year: parseInt(match.groups.year),
    month: parseInt(match.groups.month),
    day: parseInt(match.groups.day),
  };
}

console.log(parseDate("2026-04-08"));
// { year: 2026, month: 4, day: 8 }

プロンプトのコツ

正規表現生成で精度を上げるには、以下の情報をプロンプトに含めましょう。効果的なプロンプトの書き方はプロンプトを改善する5つのTipsも参考になります。

  1. マッチさせたい文字列の具体例を複数提示する
  2. マッチさせたくない文字列も明示する
  3. 利用場面(バリデーション、抽出、置換)を伝える
  4. 言語やフレームワークの制約を指定する
> 以下の条件でメールアドレスのバリデーション正規表現を作って。
> - マッチすべき: [email protected], [email protected]
> - マッチしない: @example.com, user@, [email protected]
> - TypeScriptで使う。RFC 5322に完全準拠でなくてよい。

まとめ

Claude Codeを正規表現アシスタントとして活用すると、複雑なパターンの作成時間を大幅に短縮できます。自然言語で要件を伝え、テストケースも同時に生成することで、正規表現の品質と保守性が向上します。

より高度な活用法についてはClaude Code公式ドキュメントを参照してください。

#Claude Code #正規表現 #regex #デバッグ #テスト