在 TCL 中搜索期望使用变量名不获取答案

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

我通过 Expect 脚本执行 telnet,并发送一些命令并期待以下内容。

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)

我可以将要搜索的文本保存在变量中并传递给 expect-re {....} 吗? 我希望在变量中搜索文本,然后在 expect..

中传递该变量

我试过了,但没用。

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

我认为您的问题是变量没有在大括号内展开。试试这个:

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

比较两者的区别:

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

大括号防止替换 $tests 的值,而只是将文字 $tests 作为正则表达式。引号确保您实际获得 $tests 的值。我添加了额外的大括号(使其成为 ${tests}),否则括号将被视为变量扩展的一部分。

@user108471 为您解答。这里有几个构建正则表达式的备选方案:

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"

这需要您的 expect 建立在 Tcl 8.6.2 上(它引入了 string cat 命令):使用 expect -c 'puts [info patchlevel]'

进行验证

此外,您似乎需要 (.*?)\s 中的非空白字符。这也可以用 \S* 来完成——这有点简单:

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