[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M72XGH13Z43JAFASW8YETHRT":3,"skill-same:01M72XGH13Z43JAFASW8YETHRT":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":6,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M72XGH13Z43JAFASW8YETHRT","regex-vs-llm-structured-text",null,"选择在解析结构化文本时使用正则表达式还是大型语言模型的决策框架——从正则表达式开始，仅在低置信度的边缘情况下添加大型语言模型。","SriramGandhiS\u002FSkills","SriramGandhiS","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F211849986?v=4","01M72WQCW12BYX71C6WN584TTA","Sriram S","01M72WQCWTJ2RD0ET1X31AF1RC",1,"MIT","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fdocs\u002Fzh-CN\u002Fskills\u002Fregex-vs-llm-structured-text\u002FSKILL.md",[],[],"2026-11-10 22:39:42",false,"---\nname: regex-vs-llm-structured-text\ndescription: 选择在解析结构化文本时使用正则表达式还是大型语言模型的决策框架——从正则表达式开始，仅在低置信度的边缘情况下添加大型语言模型。\norigin: ECC\n---\n\n# 正则表达式 vs LLM 用于结构化文本解析\n\n一个用于解析结构化文本（测验、表单、发票、文档）的实用决策框架。核心见解是：正则表达式能以低成本、确定性的方式处理 95-98% 的情况。将昂贵的 LLM 调用留给剩余的边缘情况。\n\n## 何时使用\n\n* 解析具有重复模式的结构化文本（问题、表单、表格）\n* 决定在文本提取时使用正则表达式还是 LLM\n* 构建结合两种方法的混合管道\n* 在文本处理中优化成本\u002F准确性权衡\n\n## 决策框架\n\n```\n文本格式是否一致且重复？\n├── 是 (>90% 遵循某种模式) → 从正则表达式开始\n│   ├── 正则表达式处理 95%+ → 完成，无需 LLM\n│   └── 正则表达式处理 \u003C95% → 仅为边缘情况添加 LLM\n└── 否 (自由格式，高度可变) → 直接使用 LLM\n```\n\n## 架构模式\n\n```\n[正则表达式解析器] ─── 提取结构（95-98% 准确率）\n    │\n    ▼\n[文本清理器] ─── 去除噪声（标记、页码、伪影）\n    │\n    ▼\n[置信度评分器] ─── 标记低置信度提取项\n    │\n    ├── 高置信度（≥0.95）→ 直接输出\n    │\n    └── 低置信度（\u003C0.95）→ [LLM 验证器] → 输出\n```\n\n## 实现\n\n### 1. 正则表达式解析器（处理大多数情况）\n\n```python\nimport re\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass ParsedItem:\n    id: str\n    text: str\n    choices: tuple[str, ...]\n    answer: str\n    confidence: float = 1.0\n\ndef parse_structured_text(content: str) -> list[ParsedItem]:\n    \"\"\"Parse structured text using regex patterns.\"\"\"\n    pattern = re.compile(\n        r\"(?P\u003Cid>\\d+)\\.\\s*(?P\u003Ctext>.+?)\\n\"\n        r\"(?P\u003Cchoices>(?:[A-D]\\..+?\\n)+)\"\n        r\"Answer:\\s*(?P\u003Canswer>[A-D])\",\n        re.MULTILINE | re.DOTALL,\n    )\n    items = []\n    for match in pattern.finditer(content):\n        choices = tuple(\n            c.strip() for c in re.findall(r\"[A-D]\\.\\s*(.+)\", match.group(\"choices\"))\n        )\n        items.append(ParsedItem(\n            id=match.group(\"id\"),\n            text=match.group(\"text\").strip(),\n            choices=choices,\n            answer=match.group(\"answer\"),\n        ))\n    return items\n```\n\n### 2. 置信度评分\n\n标记可能需要 LLM 审核的项：\n\n```python\n@dataclass(frozen=True)\nclass ConfidenceFlag:\n    item_id: str\n    score: float\n    reasons: tuple[str, ...]\n\ndef score_confidence(item: ParsedItem) -> ConfidenceFlag:\n    \"\"\"Score extraction confidence and flag issues.\"\"\"\n    reasons = []\n    score = 1.0\n\n    if len(item.choices) \u003C 3:\n        reasons.append(\"few_choices\")\n        score -= 0.3\n\n    if not item.answer:\n        reasons.append(\"missing_answer\")\n        score -= 0.5\n\n    if len(item.text) \u003C 10:\n        reasons.append(\"short_text\")\n        score -= 0.2\n\n    return ConfidenceFlag(\n        item_id=item.id,\n        score=max(0.0, score),\n        reasons=tuple(reasons),\n    )\n\ndef identify_low_confidence(\n    items: list[ParsedItem],\n    threshold: float = 0.95,\n) -> list[ConfidenceFlag]:\n    \"\"\"Return items below confidence threshold.\"\"\"\n    flags = [score_confidence(item) for item in items]\n    return [f for f in flags if f.score \u003C threshold]\n```\n\n### 3. LLM 验证器（仅用于边缘情况）\n\n```python\ndef validate_with_llm(\n    item: ParsedItem,\n    original_text: str,\n    client,\n) -> ParsedItem:\n    \"\"\"Use LLM to fix low-confidence extractions.\"\"\"\n    response = client.messages.create(\n        model=\"claude-haiku-4-5-20251001\",  # Cheapest model for validation\n        max_tokens=500,\n        messages=[{\n            \"role\": \"user\",\n            \"content\": (\n                f\"Extract the question, choices, and answer from this text.\\n\\n\"\n                f\"Text: {original_text}\\n\\n\"\n                f\"Current extraction: {item}\\n\\n\"\n                f\"Return corrected JSON if needed, or 'CORRECT' if accurate.\"\n            ),\n        }],\n    )\n    # Parse LLM response and return corrected item...\n    return corrected_item\n```\n\n### 4. 混合管道\n\n```python\ndef process_document(\n    content: str,\n    *,\n    llm_client=None,\n    confidence_threshold: float = 0.95,\n) -> list[ParsedItem]:\n    \"\"\"Full pipeline: regex -> confidence check -> LLM for edge cases.\"\"\"\n    # Step 1: Regex extraction (handles 95-98%)\n    items = parse_structured_text(content)\n\n    # Step 2: Confidence scoring\n    low_confidence = identify_low_confidence(items, confidence_threshold)\n\n    if not low_confidence or llm_client is None:\n        return items\n\n    # Step 3: LLM validation (only for flagged items)\n    low_conf_ids = {f.item_id for f in low_confidence}\n    result = []\n    for item in items:\n        if item.id in low_conf_ids:\n            result.append(validate_with_llm(item, content, llm_client))\n        else:\n            result.append(item)\n\n    return result\n```\n\n## 实际指标\n\n来自一个生产中的测验解析管道（410 个项目）：\n\n| 指标 | 值 |\n|--------|-------|\n| 正则表达式成功率 | 98.0% |\n| 低置信度项目 | 8 (2.0%) |\n| 所需 LLM 调用次数 | ~5 |\n| 相比全 LLM 的成本节省 | ~95% |\n| 测试覆盖率 | 93% |\n\n## 最佳实践\n\n* **从正则表达式开始** — 即使不完美的正则表达式也能提供一个改进的基线\n* **使用置信度评分** 来以编程方式识别需要 LLM 帮助的内容\n* **使用最便宜的 LLM** 进行验证（Haiku 类模型已足够）\n* **切勿修改** 已解析的项 — 从清理\u002F验证步骤返回新实例\n* **TDD 效果很好** 用于解析器 — 首先为已知模式编写测试，然后是边缘情况\n* **记录指标**（正则表达式成功率、LLM 调用次数）以跟踪管道健康状况\n\n## 应避免的反模式\n\n* 当正则表达式能处理 95% 以上的情况时，将所有文本发送给 LLM（昂贵且缓慢）\n* 对自由格式、高度可变的文本使用正则表达式（LLM 在此处更合适）\n* 跳过置信度评分，希望正则表达式“能正常工作”\n* 在清理\u002F验证步骤中修改已解析的对象\n* 不测试边缘情况（格式错误的输入、缺失字段、编码问题）\n\n## 适用场景\n\n* 测验\u002F考试题目解析\n* 表单数据提取\n* 发票\u002F收据处理\n* 文档结构解析（标题、章节、表格）\n* 任何具有重复模式且成本重要的结构化文本\n","# 正则表达式 vs LLM 用于结构化文本解析\n\n一个用于解析结构化文本（测验、表单、发票、文档）的实用决策框架。核心见解是：正则表达式能以低成本、确定性的方式处理 95-98% 的情况。将昂贵的 LLM 调用留给剩余的边缘情况。\n\n## 何时使用\n\n* 解析具有重复模式的结构化文本（问题、表单、表格）\n* 决定在文本提取时使用正则表达式还是 LLM\n* 构建结合两种方法的混合管道\n* 在文本处理中优化成本\u002F准确性权衡\n\n## 决策框架\n\n```\n文本格式是否一致且重复？\n├── 是 (>90% 遵循某种模式) → 从正则表达式开始\n│   ├── 正则表达式处理 95%+ → 完成，无需 LLM\n│   └── 正则表达式处理 \u003C95% → 仅为边缘情况添加 LLM\n└── 否 (自由格式，高度可变) → 直接使用 LLM\n```\n\n## 架构模式\n\n```\n[正则表达式解析器] ─── 提取结构（95-98% 准确率）\n    │\n    ▼\n[文本清理器] ─── 去除噪声（标记、页码、伪影）\n    │\n    ▼\n[置信度评分器] ─── 标记低置信度提取项\n    │\n    ├── 高置信度（≥0.95）→ 直接输出\n    │\n    └── 低置信度（\u003C0.95）→ [LLM 验证器] → 输出\n```\n\n## 实现\n\n### 1. 正则表达式解析器（处理大多数情况）\n\n```python\nimport re\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass ParsedItem:\n    id: str\n    text: str\n    choices: tuple[str, ...]\n    answer: str\n    confidence: float = 1.0\n\ndef parse_structured_text(content: str) -> list[ParsedItem]:\n    \"\"\"Parse structured text using regex patterns.\"\"\"\n    pattern = re.compile(\n        r\"(?P\u003Cid>\\d+)\\.\\s*(?P\u003Ctext>.+?)\\n\"\n        r\"(?P\u003Cchoices>(?:[A-D]\\..+?\\n)+)\"\n        r\"Answer:\\s*(?P\u003Canswer>[A-D])\",\n        re.MULTILINE | re.DOTALL,\n    )\n    items = []\n    for match in pattern.finditer(content):\n        choices = tuple(\n            c.strip() for c in re.findall(r\"[A-D]\\.\\s*(.+)\", match.group(\"choices\"))\n        )\n        items.append(ParsedItem(\n            id=match.group(\"id\"),\n            text=match.group(\"text\").strip(),\n            choices=choices,\n            answer=match.group(\"answer\"),\n        ))\n    return items\n```\n\n### 2. 置信度评分\n\n标记可能需要 LLM 审核的项：\n\n```python\n@dataclass(frozen=True)\nclass ConfidenceFlag:\n    item_id: str\n    score: float\n    reasons: tuple[str, ...]\n\ndef score_confidence(item: ParsedItem) -> ConfidenceFlag:\n    \"\"\"Score extraction confidence and flag issues.\"\"\"\n    reasons = []\n    score = 1.0\n\n    if len(item.choices) \u003C 3:\n        reasons.append(\"few_choices\")\n        score -= 0.3\n\n    if not item.answer:\n        reasons.append(\"missing_answer\")\n        score -= 0.5\n\n    if len(item.text) \u003C 10:\n        reasons.append(\"short_text\")\n        score -= 0.2\n\n    return ConfidenceFlag(\n        item_id=item.id,\n        score=max(0.0, score),\n        reasons=tuple(reasons),\n    )\n\ndef identify_low_confidence(\n    items: list[ParsedItem],\n    threshold: float = 0.95,\n) -> list[ConfidenceFlag]:\n    \"\"\"Return items below confidence threshold.\"\"\"\n    flags = [score_confidence(item) for item in items]\n    return [f for f in flags if f.score \u003C threshold]\n```\n\n### 3. LLM 验证器（仅用于边缘情况）\n\n```python\ndef validate_with_llm(\n    item: ParsedItem,\n    original_text: str,\n    client,\n) -> ParsedItem:\n    \"\"\"Use LLM to fix low-confidence extractions.\"\"\"\n    response = client.messages.create(\n        model=\"claude-haiku-4-5-20251001\",  # Cheapest model for validation\n        max_tokens=500,\n        messages=[{\n            \"role\": \"user\",\n            \"content\": (\n                f\"Extract the question, choices, and answer from this text.\\n\\n\"\n                f\"Text: {original_text}\\n\\n\"\n                f\"Current extraction: {item}\\n\\n\"\n                f\"Return corrected JSON if needed, or 'CORRECT' if accurate.\"\n            ),\n        }],\n    )\n    # Parse LLM response and return corrected item...\n    return corrected_item\n```\n\n### 4. 混合管道\n\n```python\ndef process_document(\n    content: str,\n    *,\n    llm_client=None,\n    confidence_threshold: float = 0.95,\n) -> list[ParsedItem]:\n    \"\"\"Full pipeline: regex -> confidence check -> LLM for edge cases.\"\"\"\n    # Step 1: Regex extraction (handles 95-98%)\n    items = parse_structured_text(content)\n\n    # Step 2: Confidence scoring\n    low_confidence = identify_low_confidence(items, confidence_threshold)\n\n    if not low_confidence or llm_client is None:\n        return items\n\n    # Step 3: LLM validation (only for flagged items)\n    low_conf_ids = {f.item_id for f in low_confidence}\n    result = []\n    for item in items:\n        if item.id in low_conf_ids:\n            result.append(validate_with_llm(item, content, llm_client))\n        else:\n            result.append(item)\n\n    return result\n```\n\n## 实际指标\n\n来自一个生产中的测验解析管道（410 个项目）：\n\n| 指标 | 值 |\n|--------|-------|\n| 正则表达式成功率 | 98.0% |\n| 低置信度项目 | 8 (2.0%) |\n| 所需 LLM 调用次数 | ~5 |\n| 相比全 LLM 的成本节省 | ~95% |\n| 测试覆盖率 | 93% |\n\n## 最佳实践\n\n* **从正则表达式开始** — 即使不完美的正则表达式也能提供一个改进的基线\n* **使用置信度评分** 来以编程方式识别需要 LLM 帮助的内容\n* **使用最便宜的 LLM** 进行验证（Haiku 类模型已足够）\n* **切勿修改** 已解析的项 — 从清理\u002F验证步骤返回新实例\n* **TDD 效果很好** 用于解析器 — 首先为已知模式编写测试，然后是边缘情况\n* **记录指标**（正则表达式成功率、LLM 调用次数）以跟踪管道健康状况\n\n## 应避免的反模式\n\n* 当正则表达式能处理 95% 以上的情况时，将所有文本发送给 LLM（昂贵且缓慢）\n* 对自由格式、高度可变的文本使用正则表达式（LLM 在此处更合适）\n* 跳过置信度评分，希望正则表达式“能正常工作”\n* 在清理\u002F验证步骤中修改已解析的对象\n* 不测试边缘情况（格式错误的输入、缺失字段、编码问题）\n\n## 适用场景\n\n* 测验\u002F考试题目解析\n* 表单数据提取\n* 发票\u002F收据处理\n* 文档结构解析（标题、章节、表格）\n* 任何具有重复模式且成本重要的结构化文本\n",{"name":5,"origin":24,"description":7},"ECC","master","d6ca01da0f24a3b0e26e4a8b7b66cbd25d429f5d","docs\u002Fzh-CN\u002Fskills\u002Fregex-vs-llm-structured-text",0,"https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills","https:\u002F\u002Fgithub.com\u002FSriramGandhiS","https:\u002F\u002Fsriram.website\u002F","Curious guy who keeps tinkering until something works","2026-05-20 16:21:34",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add SriramGandhiS\u002FSkills --skill regex-vs-llm-structured-text",{"tool":40,"command":41},"bunx","bunx skills add SriramGandhiS\u002FSkills --skill regex-vs-llm-structured-text",{"tool":43,"command":44},"pnpm","pnpm dlx skills add SriramGandhiS\u002FSkills --skill regex-vs-llm-structured-text","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fdocs\u002Fzh-CN\u002Fskills\u002Fregex-vs-llm-structured-text\u002FSKILL.md",true,[],[49,57,62,68,75,82],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":56},"01M732609EPJWV13PVTX3GT4TM","webgpu-threejs-tsl","Comprehensive guide for developing WebGPU-enabled Three.js applications using TSL (Three.js Shading Language). Covers WebGPU renderer setup, TSL syntax and node materials, compute shaders, post-processing effects, and WGSL integration. Use this skill when working with Three.js WebGPU, TSL shaders, node materials, or GPU compute in Three.js.","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fwebgpu-threejs-tsl\u002Fskills\u002Fwebgpu-threejs-tsl\u002FSKILL.md",[],[],"2026-11-11 15:11:14",{"skillNo":58,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":56},"01M7325XM47AGWB6K6C4VXKE6B","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fwebgpu-threejs-tsl\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":56},"01M7325WP6DES69JKC840VMFEP","verification-loop","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fweb-assets\u002Fdocs\u002Fzh-TW\u002Fskills\u002Fverification-loop\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":56},"01M7325TFQF1DZTQ6J3WGQQ1VR","tdd-workflow","Use this skill when writing new features, fixing bugs, or refactoring code. Enforces test-driven development with 80%+ coverage including unit, integration, and E2E tests.","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fweb-assets\u002Fdocs\u002Fzh-TW\u002Fskills\u002Ftdd-workflow\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":56},"01M7325RGV9AY9PK92D2V8KKPW","strategic-compact","Suggests manual context compaction at logical intervals to preserve context through task phases rather than arbitrary auto-compaction.","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fweb-assets\u002Fdocs\u002Fzh-TW\u002Fskills\u002Fstrategic-compact\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":56},"01M7325MZC28SE86E7NMCNEFS4","security-review","Use this skill when adding authentication, handling user input, working with secrets, creating API endpoints, or implementing payment\u002Fsensitive features. Provides comprehensive security checklist and patterns.","https:\u002F\u002Fgithub.com\u002FSriramGandhiS\u002FSkills\u002Fblob\u002Fmaster\u002Fweb-assets\u002Fdocs\u002Fzh-TW\u002Fskills\u002Fsecurity-review\u002FSKILL.md",[],[]]