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

Regex EXPECT脚本中的正则表达式模式匹配,regex,expect,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} {

我有一个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 glob模式为“”。不可用,正在禁用 性能助推器。

expect:“(spawn_id exp5)是否与正则表达式“(\d+)匹配?”? (无闸门,仅限RE)闸门=是RE=否
ps-ef | grep htt | grep start | wc-l

expect:ps-ef | grep htt | grep start | wc-l\r\n(spawn|u id exp5) 匹配正则表达式“(\d+”?(无闸门,仅限RE)闸门=是 re=no
11

期望值:“ps-ef | grep htt | grep start | wc-l\r\n11\r\n”(生成id exp5)匹配正则表达式“(\d+”?(无闸门,仅限RE) 门=是re=是

expect:设置expect_out(0,字符串)“ps-ef | grep htt | grep start | wc-l \r\n11\r\n“
期望:设置期望值(1,字符串)“1”
期望:设定 expect\u out(spawn\u id)“exp5”expect:set expect\u out(buffer)”ps -ef | grep htt | grep start | wc-l\r\n11theNum=1
不正常

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


提前感谢您的评论。

这是因为前导的
*
非常贪婪——因为它会尽可能多地拼凑字符,
(\d+)
部分的剩余文本是最后一位数字。这是一个演示,我还捕获了主要的“*”:

记下“1,string”和“2,string”中存储的内容

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

expect -re {\d+}
set theNum $expect_out(0,string)
或者,如果要捕获行中唯一字符的第一个数字:


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

Glenn,您的解决方案非常有效!喜欢你的回答风格:干净,恰到好处!谢谢
expect -re {\d+}
set theNum $expect_out(0,string)
expect -re {\r\n(\d+)\r\n}
set theNum $expect_out(1,string)