【问题标题】:Regex pattern match in EXPECT scriptEXPECT 脚本中的正则表达式模式匹配
【发布时间】:2023-03-09 08:37:01
【问题描述】:

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

    ....
    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 }
Gate '.(\d+).' 的 keeper glob 模式是 ''。不可用,禁用 性能助推器。

期望:“” (spawn_id exp5) 是否匹配正则表达式“.(\d+).”? (无门,仅限 RE)gate=yes re=no
ps -ef|grep htt|grep start|wc -l

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

期望:“ps -ef|grep htt|grep start|wc -l \r\n11\r\n”(spawn_id exp5) 匹配正则表达式“.(\d+).”? (无门,仅限 RE) 门=是 重新=是

expect: set expect_out(0,string) "ps -ef|grep htt|grep start|wc -l \r\n11\r\n"
expect: set expect_out(1,string) "1"
期望:设置 期望输出(spawn_id)“exp5”期望:设置期望输出(缓冲区)“ps -ef|grep htt|grep start|wc -l \r\n11\r\n"
theNum = 1
不行

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

提前感谢您的 cmets。

【问题讨论】:

    标签: regex expect


    【解决方案1】:

    这是由于前导 .* 的贪婪 - 因为这会吞下尽可能多的字符,所以 (\d+) 部分的剩余文本是 最后一个 数字。这是一个演示,其中我还捕获了前导“.*”:

    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”中存储的内容

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

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

    或者,如果您想捕获第一个数字是一行中唯一的字符

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

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

    【讨论】:

    • 格伦,您的解决方案完美运行!喜欢你的回答风格:干净利落!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    相关资源
    最近更新 更多