从tcl中的字符串中获取值

时间:2014-07-15 12:50:48

标签: regex pattern-matching tcl

我必须从指定的字符串中获取模式

这是我第一次使用tcl。与perl一样,我只需使用$1 $2 ... $n获取分组值即可。在tcl我尝试过这种方式......实际上这甚至都没有工作......

while { [gets $LOG_FILE line] >= 0 } {
    if {[regexp -inline {Getting available devices: (/.+$)} $line]} {
        puts {group0}
    }
}

1 个答案:

答案 0 :(得分:2)

使用regexp,您可以通过两种方式获取子匹配。

  1. 如果没有-inline,您必须提供足以获得您关注的子匹配的变量(第一个变量适用于整个匹配区域,如Perl中的$&):< / p>

    if {[regexp {Getting available devices: (/.+$)} $line a b]} {
        puts $b
    }
    

    ->用作整体匹配变量非常常见。它对Tcl来说完全没有特殊性,但是它使脚本更容易理解:

    if {[regexp {Getting available devices: (/.+$)} $line -> theDevices]} {
        puts $theDevices
    }
    
  2. 使用-inlineregexp会返回匹配的内容列表,而不是将它们分配给变量。

    set matched [regexp -inline {Getting available devices: (/.+$)} $line]
    if {[llength $matched]} {
        set group1 [lindex $matched 1]
        puts $group1
    }
    

    -inline表单适用于多变量foreachlassign,特别是与-all 结合使用。

    foreach {-> theDevices} [regexp -inline -all {Getting available devices: (/.+$)} $line] {
        puts $theDevices
    }