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

时间:2017-12-13 13:43:40

标签: tcl expect

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

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

=>输出为3(这是正确答案)

set tests "02 : "

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

=>输出为2(其他一些值,此值是$ expect_out(1,string)中用于搜索其他文本的旧值)

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

中传递该变量

我试过这个,但它没有用。

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

2 个答案:

答案 0 :(得分:2)

我相信你的问题是变量没有在大括号内展开。试试这个:

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

比较两者之间的区别:

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

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

答案 1 :(得分:1)

@ 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"

这要求您希望建立在Tcl 8.6.2(引入string cat命令)上:使用expect -c 'puts [info patchlevel]'进行验证

此外,您似乎希望使用(.*?)\s的非空白字符。这也可以通过\S*完成 - 这有点简单:

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