如果我想DEF_23
使用以下正则表达式进行匹配:
expect {
-re "DEF_\[0-9]*"
set result $expect_out(1,string)
}
为什么说no such element in array
?它是如何$expect_out
工作的,如何DEF
使用正则表达式捕获并将其分配给变量result
?
您正在寻找-如果您在正则表达式中捕获括号,则将填充expect_out(0,string)
数组元素。1,string
expect 手册页在expect命令的文档中记录了expect_out的使用 :
在匹配模式(或 eof 或 full_buffer)时,任何匹配的和以前不匹配的输出都保存在变量expect_out(buffer)中。最多 9 个正则表达式子字符串匹配保存在变量expect_out(1,string)到expect_out(9,string)中。如果在模式之前使用-indices标志,则 10 个字符串的开始和结束索引(以适合lrange的形式)存储在变量expect_out(X,start)和expect_out(X,end)中,其中 X 是数字,对应于缓冲区中的子字符串位置。0 是指匹配整个模式的字符串,并为 glob 模式和正则表达式模式生成。
手册页中有一个说明性示例。
看来上面的解释不准确啊!检查这个例子:
$ 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) 时测试结果相同。我错过了什么还是这是预期的行为?
Aleksandar - 如果您将匹配更改为“\ndb.*$”,它应该可以工作。
如果您打开 exp_internal 1,您将看到缓冲区包含如下内容:“ls -1 db*\r\ndbupgrade.log\r\n08:46:09”
因此,插入符号 (^) 将取消您的模式匹配。