hari prasad
hari prasad

Reputation: 35

Search in TCL expect using variable name doesn't fetch answer

I doing telnet via an Expect script, and send some command and expect the the below.

expect -re {02 : (.*?)\s}
set output $expect_out(1,string)
puts "output is $output"

=> output is 3 (this is the right answer)

set tests "02 : "

expect -re {"$tests"(.*?)\s}
set output $expect_out(1,string)
puts "output is $output"

=> output is 2 (some other value, this value is the older value present in $expect_out(1,string) that was used to search other text)

Can I save the text to be searched in a variable and pass to expect-re {....} ? I want the text to be searched in a variable, and then pass that variable in expect..

I tried this, but it didn't work.

expect -re {($tests)(.*?)\s}

Upvotes: 1

Views: 81

Answers (2)

glenn jackman
glenn jackman

Reputation: 247230

@user108471 has the answer for you. Here are a couple of alternatives to build the regex:

set tests "02 : "
set suffix {(.*?)\s}
set regex [string cat $tests $suffix]

expect -re $regex
set output $expect_out(1,string)
puts "output is $output"

This requires your expect be built on Tcl 8.6.2 (which introduced the string cat command): verify with expect -c 'puts [info patchlevel]'

Also, you appear to want non-whitespace characters with (.*?)\s. This can also be accomplished with \S* -- that's a bit simpler:

set regex "${tests}(\\S*)"

Upvotes: 1

user108471
user108471

Reputation: 2607

I believe your issue is that the variable is not being expanded within the braces. Try this instead:

expect -re "${tests}(.*?)\\s"

Compare the difference between:

puts {"$tests"(.*?)\s}
# Output: "$tests"(.*?)\s
puts "${tests}(.*?)\\s"
# Output: 02 : (.*?)\s

The braces prevent substitution of the value of $tests and instead just puts a literal $tests as the regular expression. The quotes ensure that you actually get the value of $tests. I have added additional braces (to make it ${tests}) because otherwise the parens are treated as part of the variable expansion.

Upvotes: 2

Related Questions