dsh-tool-regex:給 DSH 提供確定性正則工具

前言

在 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
羽毛球分组比赛记分
小程序二维码

欢迎使用《羽毛球分组比赛记分》微信小程序

小夜