首页 > 解决方案 > 用TCL中的方括号匹配字符串

问题描述

我正在尝试使用“regexp”进行一些字符串检查。代码 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。如何使这段代码工作?谢谢你。

标签: regextcl

解决方案


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

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

string first返回匹配的索引,索引-1表示未找到匹配项。您可以像这样轻松地使用它if

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

如果您仍然打算使用正则表达式,那么我想您可以使用帮助程序来转义非单词字符:

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

推荐阅读