regex - 用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。如何使这段代码工作?谢谢你。
解决方案
看起来您没有使用正则表达式匹配提供的任何东西并且只进行正常的字符串比较......那么为什么不只使用类似的东西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
推荐阅读
- django - Django,如何获取用户名和密码并传递给其他应用程序
- java - 如何在 maven jar 依赖项中排除 xml 文件
- .net - 在 .NET Core 3.1 中设置带有声明的 JWT 策略?
- node.js - 在生产环境(kubernetes)中为 nodejs 启用 --inspect 是个好主意吗?
- r - runCor(TTR 包)如何计算标准差 = 0 的变量的相关性?
- sas - SAS 数值比较的奇怪行为;精度问题?
- java - Log4j2 手动解析?
- matlab - 在 Matlab 中移动图像
- asp.net-mvc - 如何在MVC中单击按钮后在网页上显示弹出窗口
- javascript - 如何在 jQuery dataTables 中获取变量会话?