Regular expressions in expect

后端 未结 2 896
再見小時候
再見小時候 2021-01-19 04:26

I just started learning expect scripting.I have been trying to extract the following from my output:

core.4046140998.01.10.133211

with an e

相关标签:
2条回答
  • 2021-01-19 04:49

    Since this is expect, "core" may appear at the beginning of a line, but not at the beginning of the input string. To demonstrate:

    $ expect
    expect1.1> spawn sh
    spawn sh
    8043
    expect1.2> send "echo core.1234\r"
    expect1.3> exp_internal 1
    expect1.4> expect -re {^core.*}
    Gate keeper glob pattern for '^core.*' is 'core*'. Activating booster.
    
    expect: does "" (spawn_id exp6) match regular expression "^core.*"? Gate "core*"? gate=no
    sh-4.3$ echo core.1234
    core.1234
    sh-4.3$ 
    expect: does "sh-4.3$ echo core.1234\r\ncore.1234\r\nsh-4.3$ " (spawn_id exp6) match regular expression "^core.*"? Gate "core*"? gate=yes re=no
    expect: timed out
    expect1.5> expect -re {(?n)^core.*}
    Gate keeper glob pattern for '(?n)^core.*' is 'core*'. Activating booster.
    
    expect: does "sh-4.3$ echo core.1234\r\ncore.1234\r\nsh-4.3$ " (spawn_id exp6) match regular expression "(?n)^core.*"? Gate "core*"? gate=yes re=yes
    expect: set expect_out(0,string) "core.1234\r"
    expect: set expect_out(spawn_id) "exp6"
    expect: set expect_out(buffer) "sh-4.3$ echo core.1234\r\ncore.1234\r"
    expect1.6> puts ">>>$expect_out(0,string)<<<"
    <<<core.1234
    

    Things to note:

    • expecting -re {^core.*} did not match. We see the "timed out" message
    • note what we're attempting to match:

      expect: does "sh-4.3$ echo core.1234\r\ncore.1234\r\nsh-4.3$ " (spawn_id exp6) match regular expression "^core.*"? Gate "core*"? gate=yes re=no
      # ............^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      

      It starts with the command I sent, so using a "normal" anchor won't work

    • the next thing I expect is -re {(?n)^core.*}. This does match.

      • the (?n) is a little-used Tcl regex instruction that tells the regex engine we want "newline-sensitive" matching.
      • newline-sensitive matching means that . will not match a newline and (more relevant here) that ^ can match immediately after a newline within a multi-line string (similarly for $)
    • note that the output of my puts command looks odd. That's due to the carriage return at the end of $expect_out(0,string). Be aware of that, and use string trim as required

    The take-away lessons here are:

    • extracting the output of commands can be hard in expect because the prompt and the sent command can get in the way.
    • use expect debugging to see why your patterns aren't matching.
    0 讨论(0)
  • 2021-01-19 05:13

    You have missed a . after \.:

    ^(core)\..*(\*)$
    

    \. matches a literal . and . matches any single character.

    Or you can use the non-greedy version:

    ^(core)\.[^*]*(\*)$
    
    0 讨论(0)
提交回复
热议问题