$ expect_out如何在TCL / EXPECT中工作?

时间:2012-06-15 13:16:00

标签: regex tcl expect

如果我想使用以下正则表达式匹配DEF_23

expect {
    -re "DEF_\[0-9]*"
    set result $expect_out(1,string)
}

为什么它说数组中没有这样的元素? 这个$ expect_out如何运作?如果我想将结果指定为DEF,如何使用regexp获取DEF并分配给变量结果?

3 个答案:

答案 0 :(得分:10)

您正在寻找expect_out(0,string) - 如果您在正则表达式中捕获了括号,则会填充数组元素1,string

expect manpage记录 expect 命令文档中 expect_out 的使用:

  

在匹配模式(或eof或full_buffer)时,任何匹配和先前不匹配的输出都保存在变量 expect_out(buffer)中。最多9个regexp子串匹配保存在变量 expect_out(1,string) expect_out(9,string)中。如果在模式之前使用 -indices 标志,则10个字符串的起始和结束索引(以适合 lrange 的形式)存储在变量中expect_out(X,start) expect_out(X,end)其中X是数字,对应于缓冲区中的子字符串位置。 0表示与整个模式匹配的字符串,为glob模式和regexp模式生成。

联机帮助页中有一个说明性示例。

答案 1 :(得分:1)

上面的解释似乎并不准确! 检查此示例:

$ cat test.exp
#!/usr/bin/expect

set timeout 5
log_user 0

spawn bash

send "ls -1 db*\r"
expect {
  -re "^db.*$" {
    set bkpfile $expect_out(0,string)
  }
}

send_user "The filename is: $bkpfile\n"

close
$ ls -1 db*
dbupgrade.log
$ ./test.exp
can't read "bkpfile": no such variable
    while executing
"send_user "The filename is: $bkpfile\n""
    (file "./test.exp" line 15)
$

当使用$ expect_out(1,string)或$ expect_out(buffer)时,测试结果相同。 我错过了什么或者这是预期的行为吗?

答案 2 :(得分:0)

Aleksandar - 如果您将匹配更改为“\ ndb。* $”,它应该可以使用。

如果你打开exp_internal 1,你会看到缓冲区包含这样的内容:“ls -1 db * \ r \ n \ ndbupgrade.log \ r \ n \ n08:46:09”

因此,插入符号(^)将关闭模式匹配。