regexp tcl to search for variables

前端 未结 1 440
鱼传尺愫
鱼传尺愫 2021-01-28 01:25

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         


        
相关标签:
1条回答
  • 2021-01-28 02:08

    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.

    0 讨论(0)
提交回复
热议问题