regexp tcl to search for variables

2020-05-03 01:23发布

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"
}

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".

Thank you.

标签: regex tcl
1条回答
何必那么认真
2楼-- · 2020-05-03 01:52

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]} {

Nicer version with format:

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

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


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]} {

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

查看更多
登录 后发表回答