You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nim语言中编译后的re.Regex转字符串报错,如何解决?

解决Nim中re.Regex对象转字符串的问题

问题核心在于strformat的fmt模板需要将对象转为字符串,但re.Regex类型没有默认的字符串转换($)函数。直接访问Regex对象的pattern字段即可获取原始正则表达式字符串,这是最直接的解决方式。

修改后的代码

import re
import strformat

let R_LICENSE = re"(?i)^.*(LICENSE|COPYING).*$"

echo fmt"We are using the regex '{R_LICENSE.pattern}' to look for a license file."

编译运行验证

执行命令:

nim compile --run re2str.nim

输出结果:

We are using the regex '(?i)^.*(LICENSE|COPYING).*$' to look for a license file.

进阶优化(可选)

如果希望更便捷地直接用$R_LICENSE完成转换,可以自定义一个$运算符:

import re

func `$`(r: Regex): string =
  r.pattern

之后就能在fmt中直接写{R_LICENSE},无需额外添加.pattern。

内容的提问来源于stack exchange,提问作者hoijui

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 01:36:19