Communitygithub.com

正則表達式 vs LLM 結構化文字處理決策框架

在解析結構化文字時,決定使用正則表達式還是大型語言模型的實用框架 — 從正則表達式開始,只在邊緣案例中對低信心度項目加入大型語言模型。

正則表達式 vs LLM 結構化文字處理決策框架 是什麼?

這是一個針對開發人員和AI代理用戶的決策框架,用於在解析結構化文字(如測驗題、表單、發票或文件)時,選擇使用正則表達式或大型語言模型。核心洞察是:正則表達式能以低成本且確定性地處理95-98%的案例,因此應先以正則表達式為主,僅對剩餘的低信心度邊緣案例保留昂貴的大型語言模型呼叫。該框架支援Claude Code、Cursor、Codex等平台,提供完整的Python實作,包含正則表達式解析器、信心度評分器、大型語言模型驗證器以及混合管線。實務上,根據生產環境的資料(例如410個測驗題項目),此方法可將大型語言模型呼叫次數減少約95%,同時維持98%的正則表達式成功率。最佳實踐包括:優先從正則表達式開始、使用信心度評分識別需要大型語言模型協助的項目、選用最便宜的大型語言模型進行驗證(如Haiku等級),以及避免將所有文字直接送入大型語言模型等反模式。

相容平台✓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% 的案例。將昂貴的大型語言模型呼叫保留給其餘的邊緣案例。

何時啟動

  • 解析具有重複模式的結構化文字(問題、表單、表格)
  • 在正則表達式與大型語言模型之間決定文字提取方式
  • 建立結合兩者的混合管線
  • 最佳化文字處理中的成本/準確度取捨

決策框架

文字格式是否一致且重複?
├── 是(>90% 遵循某種模式)→ 從正則表達式開始
│   ├── 正則表達式可處理 95% 以上 → 完成,無需大型語言模型
│   └── 正則表達式處理不足 95% → 僅對邊緣案例加入大型語言模型
└── 否(自由格式、高度可變)→ 直接使用大型語言模型

架構模式

原始文字
    │
    ▼
[正則表達式解析器] ─── 提取結構(95-98% 準確率)
    │
    ▼
[文字清理器] ─── 移除雜訊(標記、頁碼、人為痕跡)
    │
    ▼
[信心度評分器] ─── 標記低信心度提取結果
    │
    ├── 高信心度(≥0.95)→ 直接輸出
    │
    └── 低信心度(<0.95)→ [大型語言模型驗證器] → 輸出

實作

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. 信心度評分

標記可能需要大型語言模型審查的項目:

@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. 大型語言模型驗證器(僅限邊緣案例)

def validate_with_llm(
    item: ParsedItem,
    original_text: str,
    client,
) -> ParsedItem:
    """使用大型語言模型修正低信心度提取結果。"""
    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'。"
            ),
        }],
    )
    # 解析大型語言模型回應並回傳修正後的項目...
    return corrected_item

4. 混合管線

def process_document(
    content: str,
    *,
    llm_client=None,
    confidence_threshold: float = 0.95,
) -> list[ParsedItem]:
    """完整管線:正則表達式 -> 信心度檢查 -> 邊緣案例用大型語言模型。"""
    # 步驟 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:大型語言模型驗證(僅針對標記項目)
    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%)
需要的大型語言模型呼叫次數~5
相較於全部使用大型語言模型的成本節省~95%
測試覆蓋率93%

最佳實踐

  • 從正則表達式開始 — 即使是不完美的正則表達式,也能為你提供一個可改進的基準
  • 使用信心度評分 以程式化方式識別需要大型語言模型協助的項目
  • 使用最便宜的大型語言模型 進行驗證(Haiku 等級的模型就足夠)
  • 絕對不要變異 已解析的項目 — 從清理/驗證步驟中回傳新實例
  • 測試驅動開發(TDD)對解析器很有效 — 先為已知模式撰寫測試,再處理邊緣案例
  • 記錄指標(正則表達式成功率、大型語言模型呼叫次數)以追蹤管線健康度

應避免的反模式

  • 當正則表達式已能處理 95% 以上的案例時,仍將所有文字送給大型語言模型(昂貴且緩慢)
  • 對自由格式、高度可變的文字使用正則表達式(此處大型語言模型更優)
  • 跳過信心度評分,期望正則表達式「剛好能運作」
  • 在清理/驗證步驟中變異已解析的物件
  • 未測試邊緣案例(格式錯誤的輸入、缺少欄位、編碼問題)

使用時機

  • 測驗/考試題目解析
  • 表單資料提取
  • 發票/收據處理
  • 文件結構解析(標題、章節、表格)
  • 任何具有重複模式且成本至關重要的結構化文字

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.

相關技能