我有一个编译好的re.Regex,我用它作为正则表达式,但我也想把它展示给用户,因为我需要它作为一个string。strformat似乎不知道如何做到这一点。
re2str.nim
import re
import strformat
let R_LICENSE = re"(?i)^.*(LICENSE|COPYING).*$"
echo fmt"We are using the regex '{R_LICENSE}' to look for a license file."编译并运行:
nim compile --run re2str.nim产出:
re2str.nim(6, 9) template/generic instantiation of `fmt` from here
/home/user/.choosenim/toolchains/nim-1.6.4/lib/pure/strformat.nim(568, 23) Error: type mismatch: got <Regex>
but expected one of:
func `$`(x: float | float32): string
...发布于 2022-11-18 07:29:58
一种解决方案是,通过保持regex单独编译的字符串来避免这个问题。
str2re.nim
import re
import strformat
let RS_LICENSE = "(?i)^.*(LICENSE|COPYING).*$"
let R_LICENSE = re(RS_LICENSE)
echo fmt"We are using the regex '{RS_LICENSE}' to look for a license file."编译并运行:
nim compile --run str2re.nim产出:
...
We are using the regex '(?i)^.*(LICENSE|COPYING).*$' to look for a license file.https://stackoverflow.com/questions/74486237
复制相似问题