Regex shell动态响应终端提示 问题.sh 应答器 正在运行:'./responder.sh' 预期成果: 实际结果:抓住“猫”的问题不回答。。。

Regex shell动态响应终端提示 问题.sh 应答器 正在运行:'./responder.sh' 预期成果: 实际结果:抓住“猫”的问题不回答。。。,regex,command-line,expect,Regex,Command Line,Expect,尝试并搜索了多种方法,但仍然不起作用。非常感谢。expect程序挂起,因为您匹配了第一个“dog”,发送了bark,然后您使用无限超时来期待eof。当然,您没有“eof”,因为shell脚本正在等待输入 您需要对循环使用exp\u continue命令,而不是while: #!/usr/bin/expect -f set timeout -1 spawn ./questions.sh expect { -re {dog \?\r\n$} { send -- "bark\r"

尝试并搜索了多种方法,但仍然不起作用。非常感谢。

expect程序挂起,因为您匹配了第一个“dog”,发送了bark,然后您
使用无限超时来期待eof
。当然,您没有“eof”,因为shell脚本正在等待输入

您需要对循环使用
exp\u continue
命令,而不是
while

#!/usr/bin/expect -f
set timeout -1
spawn ./questions.sh
expect {
    -re {dog \?\r\n$}        { send -- "bark\r"; exp_continue }
    -re {(?!dog)\S+ \?\r\n$}  { send -- "mew\r";  exp_continue }
    eof
}
我让模式更加具体:要么是“dog”要么是“notdog”,后跟空格、问号和行尾字符

exp\u continue
命令将使代码在expect命令内循环,直到遇到“eof”


我们可以让图案稍微干燥一点:

expect {
    -re {(\S+) \?\r\n$} { 
        if {$expect_out(1,string) eq "dog"} then {send "bark\r"} else {send "mew\r"} 
        exp_continue 
    }
    eof
}

你把regex和glob语法混在一起了——它们不可能都是对的。也就是说,
*dog*
是expect用于匹配的语法(fnmatch样式glob),或者
^((?!dog)。*$
是(带有否定断言的regex首先在Perl/PCRE扩展语法中首创);他们不可能都对。或者它可能是一个完全不支持
(?!…)
的不同正则表达式语法,这实际上让我觉得更可能知道
expect
的起源……也就是说,只要您的shell程序工作正常,并且只有您的expect程序(expect是TCL的派生语言,而不是shell家族语言本身)出现故障,我建议去掉
bash
shell
标签,把重点放在
expect
标签上,这是能够回答这个问题的人将居住的地方。非常感谢你!
1 dog ?
bark
Your answer is: bark
2 dog ?
bark
Your answer is: bark
3 dog ?
bark
Your answer is: bark
1 cat ?
mew
Your answer is: mew
2 cat ?
mew
Your answer is: mew
3 cat ?
mew
Your answer is: mew
1 dog ?
bark
Your answer is: bark
2 dog ?
bark
Your answer is: bark
3 dog ?
bark
Your answer is: bark
1 cat ?
#!/usr/bin/expect -f
set timeout -1
spawn ./questions.sh
expect {
    -re {dog \?\r\n$}        { send -- "bark\r"; exp_continue }
    -re {(?!dog)\S+ \?\r\n$}  { send -- "mew\r";  exp_continue }
    eof
}
expect {
    -re {(\S+) \?\r\n$} { 
        if {$expect_out(1,string) eq "dog"} then {send "bark\r"} else {send "mew\r"} 
        exp_continue 
    }
    eof
}