Communitygithub.com

Regex vs. LLM für strukturierte Textanalyse

Entscheidungsframework für die Wahl zwischen Regex und LLM beim Parsen von strukturiertem Text – beginne mit Regex, füge LLM nur für unsichere Randfälle hinzu.

Was ist Regex vs. LLM für strukturierte Textanalyse?

Dieses Skill bietet ein praktisches Entscheidungsframework für Entwickler von KI-Agenten, die strukturierten Text wie Tests, Formulare, Rechnungen oder Dokumente parsen müssen. Der Kern liegt in einer hybriden Pipeline: Regex übernimmt zuverlässig 95–98 % der Fälle deterministisch und kostengünstig. Nur für die restlichen Randfälle mit niedriger Konfidenz wird ein günstiges LLM (z. B. Claude Haiku) zur Validierung eingesetzt. Das Framework implementiert eine klare Architektur aus Regex-Parser, Textbereinigung, Konfidenz-Scorer und optionalem LLM-Validator. Es liefert konkrete Python-Codebeispiele, Metriken aus der Produktion (98 % Regex-Erfolgsrate, ~95 % Kosteneinsparung) sowie Best Practices und Anti-Patterns. Das Skill ist ideal für Claude Code, Cursor, Codex und ähnliche KI-gestützte Entwicklungsumgebungen, in denen Kosten- und Geschwindigkeitsoptimierung bei Text-Parsing-Aufgaben entscheidend ist.

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

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Was macht Regex vs. LLM für strukturierte Textanalyse?

Ein praktisches Entscheidungsframework zum Parsen von strukturiertem Text (Tests, Formulare, Rechnungen, Dokumente). Die Kernidee: Regex erledigt 95–98 % der Fälle kostengünstig und deterministisch. Hebe dir teure LLM-Aufrufe für die verbleibenden Randfälle auf.

Wann aktivieren

  • Strukturierten Text mit sich wiederholenden Mustern parsen (Fragen, Formulare, Tabellen)
  • Entscheidung zwischen Regex und LLM für Textextraktion
  • Hybride Pipelines bauen, die beide Ansätze kombinieren
  • Kosten-/Genauigkeitsabwägungen in der Textverarbeitung optimieren

Entscheidungsframework

Ist das Textformat konsistent und wiederholend?
├── Ja (>90 % folgt einem Muster) → Beginne mit Regex
│   ├── Regex schafft >95 % → Fertig, kein LLM nötig
│   └── Regex schafft <95 % → LLM nur für Randfälle hinzufügen
└── Nein (freie Form, stark variierend) → LLM direkt verwenden

Architekturmuster

Quelltext
    │
    ▼
[Regex-Parser] ─── Extrahiert Struktur (95–98 % Genauigkeit)
    │
    ▼
[Textbereiniger] ─── Entfernt Rauschen (Markierungen, Seitenzahlen, Artefakte)
    │
    ▼
[Konfidenz-Scorer] ─── Markiert Extraktionen mit niedriger Konfidenz
    │
    ├── Hohe Konfidenz (≥0,95) → Direkte Ausgabe
    │
    └── Niedrige Konfidenz (<0,95) → [LLM-Validator] → Ausgabe

Implementierung

1. Regex-Parser (erledigt den Großteil)

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]:
    """Strukturierten Text mit Regex-Mustern parsen."""
    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. Konfidenz-Scoring

Markiere Elemente, die eine LLM-Überprüfung benötigen:

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

def score_confidence(item: ParsedItem) -> ConfidenceFlag:
    """Scored die Extraktionskonfidenz und markiert Probleme."""
    reasons = []
    score = 1.0

    if len(item.choices) < 3:
        reasons.append("few_choices")
        score -= 0.3

    if not item.answer:
        reasons.append("missing_answer")
        score -= 0.5

    if len(item.text) < 10:
        reasons.append("short_text")
        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]:
    """Gibt Elemente unterhalb des Konfidenz-Schwellenwerts zurück."""
    flags = [score_confidence(item) for item in items]
    return [f for f in flags if f.score < threshold]

3. LLM-Validator (nur Randfälle)

def validate_with_llm(
    item: ParsedItem,
    original_text: str,
    client,
) -> ParsedItem:
    """Nutzt LLM zur Korrektur von Extraktionen mit niedriger Konfidenz."""
    response = client.messages.create(
        model="claude-haiku-4-5-20251001",  # Günstigstes Modell für Validierung
        max_tokens=500,
        messages=[{
            "role": "user",
            "content": (
                f"Extrahiere die Frage, die Antwortmöglichkeiten und die Antwort aus diesem Text.\n\n"
                f"Text: {original_text}\n\n"
                f"Aktuelle Extraktion: {item}\n\n"
                f"Gib korrigiertes JSON zurück, falls nötig, oder 'CORRECT', wenn es korrekt ist."
            ),
        }],
    )
    # LLM-Antwort parsen und korrigiertes Element zurückgeben...
    return corrected_item

4. Hybride Pipeline

def process_document(
    content: str,
    *,
    llm_client=None,
    confidence_threshold: float = 0.95,
) -> list[ParsedItem]:
    """Vollständige Pipeline: Regex -> Konfidenzprüfung -> LLM für Randfälle."""
    # Schritt 1: Regex-Extraktion (erledigt 95–98 %)
    items = parse_structured_text(content)

    # Schritt 2: Konfidenz-Scoring
    low_confidence = identify_low_confidence(items, confidence_threshold)

    if not low_confidence or llm_client is None:
        return items

    # Schritt 3: LLM-Validierung (nur für markierte Elemente)
    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

Metriken aus der Praxis

Aus einer Produktions-Pipeline zum Parsen von Quizfragen (410 Items):

MetrikWert
Regex-Erfolgsrate98,0 %
Elemente mit niedriger Konfidenz8 (2,0 %)
Benötigte LLM-Aufrufe~5
Kosteneinsparung im Vergleich zu reinem LLM~95 %
Testabdeckung93 %

Best Practices

  • Beginne mit Regex – selbst ein unvollkommener Regex gibt dir eine Basis, die du verbessern kannst
  • Nutze Konfidenz-Scoring, um programmatisch zu identifizieren, was LLM-Hilfe braucht
  • Verwende das günstigste LLM für die Validierung (Modelle der Haiku-Klasse reichen aus)
  • Verändere geparste Elemente niemals direkt – gib neue Instanzen aus Bereinigungs- und Validierungsschritten zurück
  • TDD funktioniert gut für Parser – schreibe zuerst Tests für bekannte Muster, dann für Randfälle
  • Protokolliere Metriken (Regex-Erfolgsrate, Anzahl LLM-Aufrufe), um die Pipeline-Gesundheit zu überwachen

Anti-Patterns (vermeiden)

  • Allen Text an ein LLM senden, wenn Regex >95 % der Fälle abdeckt (teuer und langsam)
  • Regex für freie, stark variierende Texte verwenden (LLM ist hier besser)
  • Konfidenz-Scoring überspringen und hoffen, dass Regex „einfach funktioniert“
  • Geparste Objekte während Bereinigungs-/Validierungsschritten verändern
  • Randfälle nicht testen (fehlerhafte Eingaben, fehlende Felder, Kodierungsprobleme)

Wann verwenden

  • Quiz-/Prüfungsfragen parsen
  • Formulardaten extrahieren
  • Rechnungs-/Belegverarbeitung
  • Dokumentenstruktur parsen (Kopfzeilen, Abschnitte, Tabellen)
  • Jeder strukturierte Text mit sich wiederholenden Mustern, bei dem Kosten eine Rolle spielen

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.

Verwandte Skills