前言¶
在 DSH 工作流中,模型经常要对文本做匹配判断、提取字段、执行规则替换,或解释一个 pattern 的含义。这类操作如果直接交给模型“心算”,结果难以验证;如果临时起进程写脚本,又会引入额外开销和脚本正确性风险。
下面介绍 omdsh-dev/dsh-tool-regex。它是 omdsh-dev 维护的 DSH 正则工具插件,提供测试匹配、提取捕获组、安全替换和静态解释正则含义的能力,并统一输出 JSON 文本字符串。
插件定位¶
dsh-tool-regex 是 DSH 正则工具插件:测试匹配、提取捕获组、安全替换、静态解释正则含义(不执行任何代码)。它零依赖、纯函数,采用 MIT 许可证。
仓库地址:
https://github.com/omdsh-dev/dsh-tool-regex
核心功能¶
插件注册一个 regex 工具,action 可选以下值:
1、test:判断是否匹配。
2、find:返回全部匹配的 index、完整匹配、编号捕获组 captures 和命名组 groups。
3、replace:全局安全替换,支持 $1、$2、$<name>、$$。
4、explain:静态解析 pattern 结构并给人读解释,不执行匹配。
这些 action 统一输出 JSON 文本字符串。
参数与限制¶
基础参数如下:
action:可选test、find、replace、explain。pattern:使用 JavaScript 正则语法,不含外围/。input:用于test、find、replace。replacement:用于replace,支持$1、$2、$<name>、$$。limit:用于find,默认 50,上限 1,000。
资源与超时限制如下:
- 输入长度上限:64,000 字节(UTF-8)。
pattern≤ 16KB。replacement≤ 16KB。- 输出 ≤ 1MB。
find匹配数 ≤ 1,000。test/find/replace在可终止 worker 中执行,1,000ms 预算到期返回regex: execution timed out。explain只做静态 tokenizer,不构造RegExp实例,节点数 ≤ 4,096。
安全边界¶
文档明确警告:不要对不可信的大输入使用无锚点的嵌套量词 pattern。
上述 worker 硬超时、输入长度上限、pattern / replacement / 输出 / 匹配数上限,是插件提供的防护边界。插件以当前 dsh 进程权限运行,安装前应检查源码与 MIT 许可证。
安装与启用¶
交互式 web profile 安装:
dsh plugin --profile web add github:omdsh-dev/dsh-tool-regex
安装后,先检查 profile 配置中是否出现 tool-regex:
dsh --profile web --dump-config | grep tool-regex
包内 dsh.bundle.patch 会在安装后把插件加入 profile 的 layer stack,row id 为 tool-regex。
需要注意:web 与 headless 是不同 profile;web 安装不会自动覆盖 headless;dsh run 默认使用 headless profile。
运行验证:
dsh run "使用 regex 工具测试 d+ 是否匹配 abc123"
典型用法¶
find 可用于提取全部匹配、完整匹配、编号捕获组和命名组。文档示例:
regex { action: "find", pattern: "(\\w+)@(\\w+)", input: "a@b x c@d" }
→ [{"index":0,"match":"a@b","captures":["a","b"],"groups":null},{"index":6,"match":"c@d","captures":["c","d"],"groups":null}]
replace 可用于全局安全替换,并支持 $1、$2、$<name>、$$。文档示例:
regex { action: "replace", pattern: "(\\w+) (\\w+)", input: "hello world", replacement: "$2 $1" }
→ {"result":"world hello","replaced":1}
explain 只静态解析 pattern,不执行匹配。文档示例:
regex { action: "explain", pattern: "\\d{4}-\\d{2}" }
→ [{"kind":"escape","text":"\\d","meaning":"A digit [0-9]"},{"kind":"quantifier","text":"{4}",...},...]
运行环境¶
插件要求 Node engines:
^22.19.0 || >=24.0.0
结尾¶
dsh-tool-regex 把正则判断、字段提取、安全替换和静态解释收敛为 DSH 内的确定性工具,适合需要在 DSH 工作流中验证正则行为的场景。
GitHub 地址:
https://github.com/omdsh-dev/dsh-tool-regex