Communitygithub.com

正则表达式 vs LLM 结构化文本解析决策框架

一个在解析结构化文本时,决定使用正则表达式还是大语言模型的实用决策框架:首选正则表达式,仅对低置信度的边缘情况使用LLM。

正则表达式 vs LLM 结构化文本解析决策框架 是什么?

此技能提供了一套结构化的决策框架与实现模式,帮助开发者在解析结构化文本(如测验题、表单、发票、文档)时,在正则表达式(Regex)与大语言模型(LLM)之间做出最优选择。其核心洞察是:正则表达式能以低成本、确定性的方式处理95-98%的常见情况,而耗资昂贵的LLM调用应仅保留给剩余的低置信度边缘情况。技能支持包括Claude Code、Cursor和Codex在内的AI智能体平台。实现上,它定义了包含正则解析器、文本清洗器、置信度评分器和LLM验证器的混合管道模式。通过一个清晰的决策流程图,技能指导用户首先尝试正则表达式,只有当提取成功率达到低于95%时才引入LLM进行验证。附带的生产环境数据显示,该方法相比全量使用LLM可节省约95%的成本,同时保持98%的解析成功率。

兼容平台✓Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/tree/main/skills/regex-vs-llm-structured-text

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

正则表达式 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("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]:
    """返回低于置信度阈值的项。"""
    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"Extract the question, choices, and answer from this text.\n\n"
                f"Text: {original_text}\n\n"
                f"Current extraction: {item}\n\n"
                f"Return corrected JSON if needed, or 'CORRECT' if accurate."
            ),
        }],
    )
    # 解析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/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

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.

相关技能