Communitygithub.com

regex-vs-llm-structured-text

構造化テキスト解析における正規表現とLLMの選択フレームワーク — まずは正規表現で対応し、低信頼度のエッジケースにのみLLMを追加します。

regex-vs-llm-structured-text とは?

このスキルは、クイズ、フォーム、請求書、ドキュメントなどの構造化テキストを解析する際に、正規表現とLLMを効果的に組み合わせるための意思決定フレームワークを提供します。中心的な洞察は、正規表現で95〜98%のケースを低コストかつ決定論的に処理できるという点にあります。残りのエッジケースに対してのみ、高価なLLM呼び出しを予約することで、コストと精度のトレードオフを最適化します。実装には、正規表現パーサー、信頼度スコアラー、LLMバリデーター、そしてそれらを統合するハイブリッドパイプラインが含まれます。本番環境でのクイズ解析パイプライン(410アイテム)では、正規表現の成功率98%、LLM呼び出しはわずか5回、全LLM方式と比較して約95%のコスト削減を達成しています。このフレームワークは、Claude CodeやCursorなどのAIエージェントプラットフォームで使用でき、開発者はコストを抑えながら高精度なテキスト解析を実現できます。

対応✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/regex-vs-llm-structured-text

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

構造化テキスト解析のための正規表現 vs LLM

クイズ、フォーム、請求書、ドキュメントなどの構造化テキストを解析するための実践的な意思決定フレームワーク。重要な洞察:正規表現で95〜98%のケースを低コストかつ決定論的に処理できます。残りのエッジケースにのみ高価なLLM呼び出しを予約します。

いつアクティブにするか

  • 繰り返しパターンを持つ構造化テキスト(質問、フォーム、表)の解析
  • テキスト抽出における正規表現とLLMの選択判断
  • 両方のアプローチを組み合わせたハイブリッドパイプラインの構築
  • テキスト処理におけるコスト/精度トレードオフの最適化

意思決定フレームワーク

テキスト形式は一貫しており、繰り返しパターンを持っていますか?
├── はい(>90%がパターンに従う)→ 正規表現から開始
│   ├── 正規表現で95%以上処理可能 → 完了、LLM不要
│   └── 正規表現で95%未満 → エッジケースにのみLLMを追加
└── いいえ(自由形式でばらつきが大きい)→ LLMを直接使用

アーキテクチャパターン

ソーステキスト
    │
    ▼
[正規表現パーサー] ─── 構造を抽出(95-98%の精度)
    │
    ▼
[テキストクリーナー] ─── ノイズを除去(マーカー、ページ番号、アーティファクト)
    │
    ▼
[信頼度スコアラー] ─── 低信頼度の抽出をフラグ付け
    │
    ├── 高信頼度(≥0.95)→ 直接出力
    │
    └── 低信頼度(<0.95)→ [LLMバリデーター] → 出力

実装

1. 正規表現パーサー(大部分を処理)

import re
from dataclasses import dataclass

@dataclass(frozen=True)
class ParsedItem:
    id: str
    text: str
    choices: tuple[str, ...]
    answer: str
    confidence: float = 1.0

def parse_structured_text(content: str) -> list[ParsedItem]:
    """正規表現パターンを使用して構造化テキストを解析します。"""
    pattern = re.compile(
        r"(?P<id>\d+)\.\s*(?P<text>.+?)\n"
        r"(?P<choices>(?:[A-D]\..+?\n)+)"
        r"Answer:\s*(?P<answer>[A-D])",
        re.MULTILINE | re.DOTALL,
    )
    items = []
    for match in pattern.finditer(content):
        choices = tuple(
            c.strip() for c in re.findall(r"[A-D]\.\s*(.+)", match.group("choices"))
        )
        items.append(ParsedItem(
            id=match.group("id"),
            text=match.group("text").strip(),
            choices=choices,
            answer=match.group("answer"),
        ))
    return items

2. 信頼度スコアリング

LLMによるレビューが必要な可能性のあるアイテムをフラグ付けします:

@dataclass(frozen=True)
class ConfidenceFlag:
    item_id: str
    score: float
    reasons: tuple[str, ...]

def score_confidence(item: ParsedItem) -> ConfidenceFlag:
    """抽出の信頼度をスコアリングし、問題をフラグ付けします。"""
    reasons = []
    score = 1.0

    if len(item.choices) < 3:
        reasons.append("選択肢が少なすぎる")
        score -= 0.3

    if not item.answer:
        reasons.append("回答が欠落")
        score -= 0.5

    if len(item.text) < 10:
        reasons.append("テキストが短すぎる")
        score -= 0.2

    return ConfidenceFlag(
        item_id=item.id,
        score=max(0.0, score),
        reasons=tuple(reasons),
    )

def identify_low_confidence(
    items: list[ParsedItem],
    threshold: float = 0.95,
) -> list[ConfidenceFlag]:
    """信頼度しきい値を下回るアイテムを返します。"""
    flags = [score_confidence(item) for item in items]
    return [f for f in flags if f.score < threshold]

3. LLMバリデーター(エッジケースのみ)

def validate_with_llm(
    item: ParsedItem,
    original_text: str,
    client,
) -> ParsedItem:
    """LLMを使用して低信頼度の抽出を修正します。"""
    response = client.messages.create(
        model="claude-haiku-4-5-20251001",  # バリデーションには最も安価なモデル
        max_tokens=500,
        messages=[{
            "role": "user",
            "content": (
                f"このテキストから質問、選択肢、回答を抽出してください。\n\n"
                f"テキスト: {original_text}\n\n"
                f"現在の抽出結果: {item}\n\n"
                f"正確な場合は修正されたJSONを、または'CORRECT'を返してください。"
            ),
        }],
    )
    # LLMの応答を解析し、修正されたアイテムを返します...
    return corrected_item

4. ハイブリッドパイプライン

def process_document(
    content: str,
    *,
    llm_client=None,
    confidence_threshold: float = 0.95,
) -> list[ParsedItem]:
    """完全なパイプライン: 正規表現 → 信頼度チェック → エッジケースにはLLM"""
    # ステップ1: 正規表現による抽出(95-98%を処理)
    items = parse_structured_text(content)

    # ステップ2: 信頼度スコアリング
    low_confidence = identify_low_confidence(items, confidence_threshold)

    if not low_confidence or llm_client is None:
        return items

    # ステップ3: LLMバリデーション(フラグ付けされたアイテムのみ)
    low_conf_ids = {f.item_id for f in low_confidence}
    result = []
    for item in items:
        if item.id in low_conf_ids:
            result.append(validate_with_llm(item, content, llm_client))
        else:
            result.append(item)

    return result

実績のあるメトリクス

本番環境のクイズ解析パイプライン(410アイテム)より:

メトリクス値
正規表現の成功率98.0%
低信頼度アイテム8 (2.0%)
必要なLLM呼び出し~5
全LLM方式と比較したコスト削減~95%
テストカバレッジ93%

ベストプラクティス

  • まずは正規表現から — 不完全な正規表現でも、改善のベースラインとなります
  • 信頼度スコアリングを使用 して、LLMの支援が必要なものをプログラムで特定します
  • 最も安価なLLMをバリデーションに使用(Haikuクラスのモデルで十分)
  • 解析済みアイテムを決して変更しない — クリーニング/バリデーション手順では新しいインスタンスを返します
  • パーサーにはTDDが効果的 — まず既知のパターンのテストを書き、次にエッジケースのテストを書きます
  • メトリクスを記録(正規表現成功率、LLM呼び出し回数)してパイプラインの健全性を追跡します

避けるべきアンチパターン

  • 正規表現で95%以上処理できるケースで、すべてのテキストをLLMに送信する(高コストで低速)
  • 自由形式でばらつきの大きいテキストに正規表現を使用する(LLMの方が適している)
  • 信頼度スコアリングを省略し、正規表現が「うまく機能する」と期待する
  • クリーニング/バリデーション中に解析済みオブジェクトを変更する
  • エッジケース(不正な入力、欠落フィールド、エンコーディングの問題)をテストしない

いつ使用するか

  • クイズ/試験問題の解析
  • フォームデータの抽出
  • 請求書/領収書の処理
  • ドキュメント構造の解析(ヘッダー、セクション、表)
  • コストが重要となる繰り返しパターンを持つ構造化テキスト全般

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

関連スキル