问题描述
我正在尝试使用“ regexp”进行某些字符串检查。代码1可以工作,但是如果$ ref来自文件则失败。下面是代码:
代码1正常工作:
set foo "input \[1:0\]"
regexp {input \[} $foo
## ref_file包含以下字符串:
输入[
代码:
set foo "input \[1:0\]"
set fi [open ref_file r]
gets $fi ref
regexp $ref $foo
我无法控制ref_file。如何使此代码起作用?谢谢。
解决方法
您似乎没有使用regexp匹配提供的任何功能,并且仅进行普通的字符串比较...所以为什么不只使用string first
之类的东西呢?
set foo "input \[1:0\]"
string first {input [} $foo
string first
返回匹配项的索引,索引-1
表示未找到匹配项。您可以像这样在if
中轻松使用它:
if {[string first $ref $foo] > -1} {
...
}
如果您仍然打算使用regexp,那么我想您可以使用帮助程序来转义非单词字符:
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