【问题标题】:Expect regex number pattern期望正则表达式数字模式
【发布时间】:2013-08-14 21:49:02
【问题描述】:

我遇到了一个期望脚本的问题。我想捕获命令的输出何时为“0”并与其他数字或链(如“000”或“100”)区分开来

我的代码是:

#!/usr/bin/expect -f
set timeout 3
spawn bash send "echo 0\n" 
expect {
-regexp {^0$} { send_user "\nzero\n" }  
-re {\d+} { send_user "\number\n"}
}
send "exit\n"

我有以下回应:

spawn bash
echo 0

number

但以下正则表达式不起作用:

-regexp {^0$} { send_user "\nzero\n" }

如果我将其更改为:

-regexp {0} { send_user "\nzero\n" }

有效,但它也捕获“00”“10”“1000”等。

send "echo 100\n"
expect {
    -regexp {0} { send_user "\nzero\n" }
    -re {\d+} { send_user "\nnumber\n"}
}

结果:

spawn bash
echo 10

zero

我不知道我做错了什么,也没有从谷歌的帮助中找到任何东西。我还搜索了此处解决的类似问题,但我无法使其在我的代码上运行。

更新

我尝试了建议的修复代码:

#!/usr/bin/expect -f
set timeout 3
spawn bash
send "echo 0\n"
expect {
    -regexp {\b0\b} { send_user "\nzero\n" }
    -re {\d+} { send_user "\nnumber\n"}
}
send "exit\n"

但我仍然有这样的回应:

spawn bash
echo 0

number

更新 2

我也试过这条线:

 -regexp {"^0\n$"} { send_user "\nzero\n" }

但我仍然得到相同的结果。

提前致谢

【问题讨论】:

    标签: regex linux unix expect


    【解决方案1】:

    我可以解决问题:

    #!/usr/bin/expect -f
    set timeout 3
    
    spawn bash
    send "echo 0\n"
    expect -re "(\\d+)" {
        set result $expect_out(1,string)
    }
    if { $result == 0 } {
        send_user "\nzero\n";
    } else {
        send_user "\nnumber\n";
    }
    
    send "exit\n"
    

    【讨论】:

      【解决方案2】:

      快速浏览了 expect 的文档:

      但是,由于 expect 不是面向行的,这些字符匹配当前在 expect 匹配缓冲区中的数据的开头和结尾(而不是行)。

      您的正则表达式应该考虑到您有换行符这一事实。

      如果你的数据是0\n,那么你可以使用"^0\n$"

      【讨论】:

      • 我尝试了你的方法,但我无法成功。我真的不知道我做错了什么。
      • 我唯一能想到的是“回声”实际上并没有得到处理。要对此进行测试,请在正则表达式中尝试 {echo},看看它会给你带来什么。
      【解决方案3】:

      尝试使用单词边界:\b0\b

      【讨论】:

      • \b 匹配 TCL 中的退格字符。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-01
      相关资源
      最近更新 更多