Expect中的正则表达式

8

我刚开始学习expect脚本编程。我一直在尝试从输出中提取以下内容:

core.4046140998.01.10.133211

使用以下命令的expect脚本,请问我哪里错了?我想要将整个字符串即(core.4046140998.01.10.133211*)存储到一个变量中,并对其执行一些操作。

expect -re {^(core)\.*} {puts $expect_out(0,string)}

我需要导入任何包才能使这个工作吗?


^(core)\..*(\*)$ - rock321987
好的...那么expect_out(0,string)的输出是什么? - john
核心.4046140998.01.10.133211* - rock321987
2个回答

12

由于这是expect,"core"可能出现在一行的开头,但不会出现在输入字符串的开头。举个例子:

$ 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

需要注意的事项:

  • 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
这里的经验教训如下:
  • 在expect中提取命令输出可能很困难,因为提示符和发送的命令可能会妨碍提取。
  • 使用expect调试功能查看为什么模式不匹配。

2
您在\.后面漏掉了一个.
^(core)\..*(\*)$

\.可以匹配一个字面上的.,而.可以匹配任意单个字符。

或者你可以使用非贪婪版本:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接