为什么期望不能匹配`[0-9]`?
why expect cannot match `[0-9]`?
从下面的脚本我们可以看到一个简单的数字不能被[0-9]匹配,但是在regexp文档中,它说支持这个。为什么我的版本不起作用?
#!/bin/expect
set timeout 20
set remote_cmd_prompt_regex "> $"
spawn bash --noprofile --norc
send "PS1='> '\r"
expect {
-regexp "$remote_cmd_prompt_regex" {
puts "Host ->$expect_out(buffer)"
send "echo 99\r"
# match with .* works
expect -regexp ".*\n(.+)\n$remote_cmd_prompt_regex"
puts "regex group ->$expect_out(1,string)"
send "echo 89\r"
# match with [0-9] does not work why?
expect -regexp ".*\n(\[0-9]+)\n$remote_cmd_prompt_regex"
puts "regex group ->$expect_out(1,string)"
}
timeout {
puts "Timeout error!"
exit 1
}
}
通常(在 canonical pty 模式下),每个发送到 pty 的 \n
都会被转换为 \r\n
所以你需要改变 \n
到 RE 模式中的 \r\n
。示例:
[STEP 101] # cat foo.exp
#!/usr/bin/expect
set ps_re "> $"
spawn -noecho bash --noprofile --norc
expect bash
send "PS1='> '\r"
expect -re $ps_re
for { set i 10 } { $i < 15 } { incr i } {
send "echo $i\r"
expect -re ".*\r\n(\[0-9]+)\r\n$ps_re"
}
send "exit\r"
expect eof
[STEP 102] # expect foo.exp
bash-5.0# PS1='> '
> echo 10
10
> echo 11
11
> echo 12
12
> echo 13
13
> echo 14
14
> exit
exit
[STEP 103] #
从下面的脚本我们可以看到一个简单的数字不能被[0-9]匹配,但是在regexp文档中,它说支持这个。为什么我的版本不起作用?
#!/bin/expect
set timeout 20
set remote_cmd_prompt_regex "> $"
spawn bash --noprofile --norc
send "PS1='> '\r"
expect {
-regexp "$remote_cmd_prompt_regex" {
puts "Host ->$expect_out(buffer)"
send "echo 99\r"
# match with .* works
expect -regexp ".*\n(.+)\n$remote_cmd_prompt_regex"
puts "regex group ->$expect_out(1,string)"
send "echo 89\r"
# match with [0-9] does not work why?
expect -regexp ".*\n(\[0-9]+)\n$remote_cmd_prompt_regex"
puts "regex group ->$expect_out(1,string)"
}
timeout {
puts "Timeout error!"
exit 1
}
}
通常(在 canonical pty 模式下),每个发送到 pty 的 \n
都会被转换为 \r\n
所以你需要改变 \n
到 RE 模式中的 \r\n
。示例:
[STEP 101] # cat foo.exp
#!/usr/bin/expect
set ps_re "> $"
spawn -noecho bash --noprofile --norc
expect bash
send "PS1='> '\r"
expect -re $ps_re
for { set i 10 } { $i < 15 } { incr i } {
send "echo $i\r"
expect -re ".*\r\n(\[0-9]+)\r\n$ps_re"
}
send "exit\r"
expect eof
[STEP 102] # expect foo.exp
bash-5.0# PS1='> '
> echo 10
10
> echo 11
11
> echo 12
12
> echo 13
13
> echo 14
14
> exit
exit
[STEP 103] #