【问题标题】:Search in TCL expect using variable name doesn't fetch answer在 TCL 中搜索期望使用变量名不会获取答案
【发布时间】:2018-05-27 10:16:45
【问题描述】:

我通过 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}

【问题讨论】:

  • 您的直觉是正确的,我希望您能得到答案……但是 小心!!! 分段构建 RE 时必须小心。

标签: tcl expect


【解决方案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*)"

【讨论】:

  • 我还没有测试这个..非常感谢你
【解决方案2】:

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

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

比较两者的区别:

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

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

【讨论】:

  • expect 的一些特性会使这变得更难(在某些情况下它会做“聪明”的事情),但它应该像你所说的那样工作。
猜你喜欢
  • 2015-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多