Pythonizer
Pythonizer

Reputation: 1194

Getting value from a string in tcl

I have to get a patter from the specified string

This is first time I'm using tcl. Like in perl, I can simply get the grouped value with $1 $2 ... $n. In tcl I've tried this way ... actually this didn't even work...

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

Upvotes: 0

Views: 408

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137567

With regexp, you have two ways to get submatches out.

  1. Without -inline, you have to supply variables sufficient to get the submatch you care about (with the first such variable being for the whole matched region, like $& in Perl):

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

    It's pretty common to use -> as an overall-match variable. It's totally non-special to Tcl, but it makes the script mnemonically easier to grok:

    if {[regexp {Getting available devices: (/.+$)} $line -> theDevices]} {
        puts $theDevices
    }
    
  2. With -inline, regexp returns a list of things that were matched instead of assigning them to variables.

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

    The -inline form works very well with multi-variable foreach and lassign, especially in combination with -all.

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

Upvotes: 3

Related Questions