gpt4 book ai didi

regex - 在 Expect 的正则表达式模式匹配中访问我的捕获组到变量

转载 作者:行者123 更新时间:2023-12-04 02:46:22 27 4
gpt4 key购买 nike

我无法让它工作,我也不确定为什么。我有一行,行尾的数字之间有空格。我需要 Expect 匹配这一行并将数字和空格放入一个捕获组中,我需要稍后在我的脚本中访问该捕获组。

示例行是:这是一行 2 4 5 6

我的 expect -re 语句:expect -re {^this\sis\sa\sline((\s\d)+$)}

然后我尝试使用 $expect_out(1,string) 访问捕获组

如果我检查 http://gskinner.com/RegExr/它说匹配组 1 是“2 4 5 6”,所以我很确定模式匹配正确,我希望在 $expect_out(1,string) 中看到“2 4 5 6”,对吗?

但是,当我运行 expect 脚本时,我看到:

expect: does " \u001b[Js\u001b[Jt\u001b[Jr\u001b[Je\u001b[Ja\u001b[Jm\u001b[Js\u001b[J\r\n\u001b[H\u001b[J\r\n\r\n\r\n\r\this is a line 2 4 5 6\r\n\r\nSelect which option you would    like to change\r\nusing the index number: " (spawn_id exp5) match regular expression "^this\sis\sa\sline((\s\d)+$)"? Gate "this?is?a?line*"? gate=yes re=no
expect: timed out
can't read "expect_out(1,string)": no such element in array
while executing
"set streams $expect_out(1,string)"
(file "check-config" line 35)

如何将“2 4 5 6”(或“2 4 5 6”)放入一个变量中以便稍后在我的 expect 脚本中使用?

另外,虽然我引起了你的注意,Gate=Yes re=No 是什么意思?我假设 re=No 表示正则表达式不匹配,但是 Expect 世界中的 Gate 是什么?

最佳答案

问题是您在正则表达式中包含了行 anchor ^$。您尝试匹配的字符串显然是多行字符串,但 Tcl 的默认匹配将换行符视为常规字符。另一个复杂的因素是 Tcl 将换行符视为 \n 但 expect 使用 \r\n 作为行终止符。

如果启用 newline sensitive matching在正则表达式中考虑回车符,您可能会发现此正则表达式有效:(?n)^this\sis\sa\sline((?:\s\d)+)\r?$

测试:

$ expect <<END
spawn sh -c {echo foo; echo "this is a line 2 4 5 6"; echo bar}
exp_internal 1
expect -re {(?n)^this\sis\sa\sline((?:\s\d)+)\r?$}
END
spawn sh -c echo foo; echo "this is a line 2 4 5 6"; echo bar
Gate keeper glob pattern for '(?n)^this\sis\sa\sline((?:\s\d)+)\r?$' is 'this?is?a?line*'. Activating booster.

expect: does "" (spawn_id exp4) match regular expression "(?n)^this\sis\sa\sline((?:\s\d)+)\r?$"? Gate "this?is?a?line*"? gate=no
foo

expect: does "foo\r\n" (spawn_id exp4) match regular expression "(?n)^this\sis\sa\sline((?:\s\d)+)\r?$"? Gate "this?is?a?line*"? gate=no
this is a line 2 4 5 6
bar

expect: does "foo\r\nthis is a line 2 4 5 6\r\nbar\r\n" (spawn_id exp4) match regular expression "(?n)^this\sis\sa\sline((?:\s\d)+)\r?$"? Gate "this?is?a?line*"? gate=yes re=yes
expect: set expect_out(0,string) "this is a line 2 4 5 6\r"
expect: set expect_out(1,string) " 2 4 5 6"
expect: set expect_out(spawn_id) "exp4"
expect: set expect_out(buffer) "foo\r\nthis is a line 2 4 5 6\r"

关于regex - 在 Expect 的正则表达式模式匹配中访问我的捕获组到变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18747304/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com