匹配方括号中的字符串的语法(如“[a string]”)?

Syntax to match a string in square bracktets (like `[a string]`)?

我对期望(和 TCL)很陌生,但对编程并不陌生。 但是我正在解决一个我无法解决的问题(使用 expect 5.45):

我想匹配(expect)一个像[detached from ...]这样的字符串,但是没有成功:

显然我不能使用 -ex(act) 因为 ... 部分是可变的。

因为双引号,你需要:

expect -gl  "\\[detached from *\\]"

前 2 个斜线用于在模式中放置一个文字斜线。
第三个斜杠是为了避免括号被解释为命令替换。

更简单的方法是使用大括号(Tcl 相当于 shell 单引号

expect -gl  {\[detached from *\]}

给出我自己的替代答案(按反斜杠的数量排序):

  • -gl "[detached from *]" 执行 命令替换 (调用名为 detached 的函数,其中 from* 被视为参数函数。
  • -gl "\[detached from *\]"确实阻止了命令替换,但是[为匹配引擎引入了一个字符class,所以字符串不会按字面匹配。
  • -gl "\[detached from *\]"[detached from *]前面加了一个文字\(仍被解释为命令替换.
  • -gl "\\[detached from *\\]" 添加文字 \(留下 \[...),因此也 转义 命令替换,因此匹配引擎将看到 \[...\],按字面意思处理 [(而不是字符 class 的开头)。