EXPECT脚本中的正则表达式模式匹配

时间:2019-07-09 15:40:16

标签: regex expect

我有一个EXPECT脚本来监视IBMIHS服务器上的http pid:

    ....
    send "ps -ef|grep htt|grep start|wc -l \r"
    expect {
       -re {.*(\d+).*} {

          set theNum $expect_out(1,string)
      }
    }

    puts "theNum = $theNum"

    if {$theNum > 8} {
      puts "it is ok"
    } else {
      puts "it is not ok"
    }
....

send "ps -ef|grep htt|grep start|wc -l \r"生成:

  
    

发送:将{ps -ef | grep htt | grep start | wc -l \ r“发送到{exp5}
门     '。(\ d +)。'的keeper全局模式为''。无法使用,请停用     性能提升器。

         

期望:“”(spawn_id exp5)是否匹配正则表达式“。(\ d +)。”?     (无门,仅适用于RE)gate = yes re = no
ps -ef | grep htt | grep start | wc -l <​​/ p>          

期望:是否执行“ ps -ef | grep htt | grep start | wc -l \ r \ n”(spawn_id exp5)     匹配正则表达式“。(\ d +)。”? (无门,仅RE)门=是     re = no
11

         

期望:“ ps -ef | grep htt | grep开始| wc -l \ r \ n 11 \ r \ n”(spawn_id     exp5)匹配正则表达式“。(\ d +)。”? (无门,仅限RE)     gate = yes re = yes

  
     

期望:设置Expect_out(0,string)“ ps -ef | grep htt | grep start | wc -l   \ r \ n 11 \ r \ n“
期望:设置Expect_out(1,string)” 1“
  期望:设置   Expect_out(spawn_id)“ exp5” Expect:设置Expect_out(buffer)“ ps   -ef | grep htt | grep start | wc -l \ r \ n 11 \ r \ n“
theNum = 1
不好

命令行实际上返回一个数字“ 11 ”,但是(\d+)却捕获了一个'1'

您的评论会受到赞赏。

1 个答案:

答案 0 :(得分:2)

这是由于前导.*的贪婪-因为它会尽可能多地包含字符,(\d+)部分剩余的文本是 last 位。这是一个演示,其中我还捕获了前导的“。*”:

expect1.11> exp_internal 1
expect1.12> spawn sh -c {echo foo; echo 1234; echo bar}
spawn sh -c echo foo; echo 1234; echo bar
parent: waiting for sync byte
parent: telling child to go ahead
parent: now unsynchronized from child
spawn: returns {78523}
78523
expect1.13> expect -re {(.*)(\d+).*}
Gate keeper glob pattern for '(.*)(\d+).*' is ''. Not usable, disabling the performance booster.

expect: does "" (spawn_id exp10) match regular expression "(.*)(\d+).*"? (No Gate, RE only) gate=yes re=no
foo
1234
bar

expect: does "foo\r\n1234\r\nbar\r\n" (spawn_id exp10) match regular expression "(.*)(\d+).*"? (No Gate, RE only) gate=yes re=yes
expect: set expect_out(0,string) "foo\r\n1234\r\nbar\r\n"
expect: set expect_out(1,string) "foo\r\n123"
expect: set expect_out(2,string) "4"
expect: set expect_out(spawn_id) "exp10"
expect: set expect_out(buffer) "foo\r\n1234\r\nbar\r\n"

请注意存储在“ 1,string”和“ 2,string”中的内容

解决方案是简化您的正则表达式。如果您只想捕获第一组数字,请使用

expect -re {\d+}
set theNum $expect_out(0,string)

或者如果您想捕获一行中唯一的字符的前几个数字

expect -re {\r\n(\d+)\r\n}
set theNum $expect_out(1,string)

这里的一个教训是,您通常不需要在正则表达式模式中使用开头和结尾的.*通配符:只需关注需要捕获所需文本的内容即可。