在 TCL 中用方括号匹配字符串

match the strings with rectangular brackets in TCL

我正在尝试使用“正则表达式”进行一些字符串检查。代码 1 有效,但如果 $ref 来自文件则失败。下面是代码:

代码 1 工作正常:

set foo "input \[1:0\]"
regexp {input \[} $foo

代码 2,$ref 来自文件:

##ref_file 包含此字符串:

输入[

代码:

set foo "input \[1:0\]"
set fi [open ref_file r]
gets $fi ref
regexp $ref $foo

我无法控制 ref_file。如何使这段代码工作?谢谢。

看起来您没有使用正则表达式匹配提供的任何东西,并且只进行正常的字符串比较...那么为什么不使用 string first 之类的东西呢?

set foo "input \[1:0\]"
string first {input [} $foo

string first returns 匹配的索引,-1 的索引表示没有找到匹配。您可以像这样在 if 中轻松使用它:

if {[string first $ref $foo] > -1} {
    ...
}

如果您仍然打算使用正则表达式,那么我想您可以使用辅助过程来转义 non-word 个字符:

proc regesc {text} {
    regsub -all {\W} $text {\&}
}

set foo "input \[1:0\]"
set fi [open ref_file r]
gets $fi ref
regexp [regesc $ref] $foo