简体   繁体   中英

TCL/Regex - Getting values from multiple lines

This is my output:

Signal Quality  = 100
Signal Strength = -49
Noise Level     = -96

I am trying to get all three numeric values (ie, 100, -49, -96). I will be adding and subtracting these values, so I need each in its own variable?

These numbers are dynamic and could be a negative number.

Using the code below, I could grab one at the time, but how would a go about grabbing all 3 numbers?

expect {                    
    -re {Strength = +(.*)\s+Noise} {
        set RSSI $expect_out(1,string)
    }
    puts "Signal Strength = $RSSI"

Thanks for your help!

To get all three values in the one expect call, you need a little trickiness.

# Initialize to an empty array
unset myAry
array set myAry {}

# Now let's expect some stuff!
expect {
    -re {(\w+)\s+=\s+(-?\d+)} {
        # Found it; stuff in an array
        set myAry($expect_out(1,string)) $expect_out(2,string)
        # TRICKY! Keep waiting if we've not yet got all three values
        if {[array size myAry] < 3} {
            exp_continue
        }
    }
}

With that output from the spawned process, that'll set myAry(Quality) to 100 , myAry(Strength) to -49 , and myAry(Level) to -96 . To use both words, use this as your pattern:

{(\w+\s+\w+)\s+=\s+(-?\d+)}

and then you'll probably want to strip the spaces:

set key [string map {{ } {}} $expect_out(1,string)]
set myAry($key) $expect_out(2,string)
# Now that optionally-keep-waiting stanza from above

That can, of course, be a one-liner. I just don't like my lines to be so long usually.

Not sure about tcl regex's but something like this might work.
The numbers are in capture groups 1,2,3 in order.
Need Dot-All or add (?s) or change ' . ' to [\\S\\s]

 #  Quality\s*=\s*([+-]?\s*\d+)\s*.*?Strength\s*=\s*([+-]?\s*\d+).*?Level\s*=\s*([+-]?\s*\d+)


 Quality \s* = \s* 
 ( [+-]? \s* \d+ )              # (1)
 \s* 
 .*? 
 Strength \s* = \s* 
 ( [+-]? \s* \d+ )              # (2)
 .*? 
 Level \s* = \s* 
 ( [+-]? \s* \d+ )              # (3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM