regexp tcl 搜索变量 [英] regexp tcl to search for variables

查看:41
本文介绍了regexp tcl 搜索变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 {if loop} 中使用 regexp 命令查找匹配的模式.仍然是 tcl 的新手.代码如下所示:

I am trying to find the matching pattern using regexp command in the {if loop} . Still a newbie in tcl. The code is as shown below:

set A 0;
set B 2;
set address "my_street[0]_block[2]_road";
if {[regexp {street\[$A\].*block\[$B\]} $address]} {
puts "the location is found"
}

我期望结果返回找到位置",因为 $address 包含匹配的 A 和 B 变量.我希望能够更改 $address 列表的 A 和 B 编号.但我无法得到返回找到位置"的结果.

I am expecting the result to return "the location is found" as the $address contain matching A and B variables. i am hoping to able to change the A and B number for a list of $address. but I am not able to get the result to return "the location is found".

谢谢.

推荐答案

Tcl 的正则表达式引擎不进行变量插值.(应该吗?也许吧.虽然不是.)这意味着您需要在通用级别执行此操作,这通常很烦人,但在这里可以,因为变量只有数字,而这些数字本身从不是 RE 元字符.

Tcl's regular expression engine doesn't do variable interpolation. (Should it? Perhaps. It doesn't though.) That means that you need to do it at the generic level, which is in general quite annoying but OK here as the variables only have numbers in, which are never RE metacharacters by themselves.

基本版本(有很多.反斜杠.):

Basic version (with SO. MANY. BACKSLASHES.):

if {[regexp "street\\\[$A\\\].*block\\\[$B\\\]" $address]} {

带有格式的更好的版本:

if {[regexp [format {street\[%d\].*block\[%d\]} $A $B] $address]} {

您也可以使用 subst -nocommands -nobackslashes 但这变得不那么优雅了.

You could also use subst -nocommands -nobackslashes but that's getting less than elegant.

如果需要支持通用替换,使用regsub来做保护就足够了.

If you need to support general substitutions, it's sufficient to use regsub to do the protection.

proc protect {string} {
    regsub -all {\W} $string {\\&}
}

# ...

if {[regexp [format {street\[%s\].*block\[%s\]} [protect $A] [protect $B]] $address]} {

当您知道自己正在将字母数字替换到 RE 中时,这就有点矫枉过正了.

It's overkill when you know you're working with alphanumeric substitutions into the RE.

这篇关于regexp tcl 搜索变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆