如何在右括号后匹配冒号
How to match a colon after a close bracket
为什么以下不匹配:
expect {
timeout {puts timedout\n}
\[1\]: {puts matched\n}
}
> expect test.tcl
[1]:
timedout
如果我更改它并删除冒号,则匹配有效:
expect {
timeout {puts timedout\n}
\[1\] {puts matched\n}
}
$ expect test.tcl
[1]
matched
或者如果我去掉第一个括号
expect {
timeout {puts timedout\n}
1\]: {puts matched\n}
}
然后匹配:
$ expect test.tcl
1]:
matched
不是:
的问题,而是[
的问题。
[
对于Tcl
和Expect
模式匹配器来说都是特殊的,所以它特别混乱。要匹配文字 [
,您必须从 Tcl
反斜杠一次,然后再反斜杠一次,以便在模式匹配期间它不会被视为范围。当然,第一个反斜杠必须反斜杠,以防止它把下一个反斜杠变成文字反斜杠!
expect "\\[" ; #matches literal '['
所以,你的代码应该是,
expect {
timeout {puts timedout\n}
\\[1]: {puts matched\n}
}
您可以在 ]
前加一个反斜杠,如果这样会让您感觉良好,但事实并非如此
必要的。由于在
双引号字符串,右括号没有什么特别的发生。它代表自身并传递给 Expect
命令,然后在命令中将其解释为范围的末尾。
下一组示例将 [
的行为显示为以不同数量的反斜杠开头的模式。如果 [
没有以反斜杠作为前缀,则 Tcl
会将后面的内容解释为命令。对于这些示例,假设有一个名为 XY
的过程 returns 字符串 n*w
.
expect" [XY]" ; # matches n followed by anything
expect "\[XY]" ; # matches X or Y
expect "\[XY]" ; # matches n followed by anything followed by w
expect "\\[XY]" ; # matches [XYl
expect "\\[XY]" ; # matches \ followed by n followed ...
expect "\\\[XY]" ; # matches sequence of \ and X or Y
\[XY]
案例值得仔细研究。 Tcl
将第一个反斜杠解释为表示第二个是文字字符。 Tcl
然后生成 n*w
作为 XY 命令的结果。模式匹配器最终看到的是四个字符串 n*w
。模式匹配器以通常的方式对此进行解释。反斜杠表示 n
将按字面匹配(即使没有反斜杠,它也会匹配,因为 n 对于模式匹配器来说并不特殊)。
来源 : Exploring Expect
对我有用的模式:
-exact {[1]:}
-exact "\[1]:"
{\[1]:}
"\\[1]:"
为什么以下不匹配:
expect {
timeout {puts timedout\n}
\[1\]: {puts matched\n}
}
> expect test.tcl
[1]:
timedout
如果我更改它并删除冒号,则匹配有效:
expect {
timeout {puts timedout\n}
\[1\] {puts matched\n}
}
$ expect test.tcl
[1]
matched
或者如果我去掉第一个括号
expect {
timeout {puts timedout\n}
1\]: {puts matched\n}
}
然后匹配:
$ expect test.tcl
1]:
matched
不是:
的问题,而是[
的问题。
[
对于Tcl
和Expect
模式匹配器来说都是特殊的,所以它特别混乱。要匹配文字 [
,您必须从 Tcl
反斜杠一次,然后再反斜杠一次,以便在模式匹配期间它不会被视为范围。当然,第一个反斜杠必须反斜杠,以防止它把下一个反斜杠变成文字反斜杠!
expect "\\[" ; #matches literal '['
所以,你的代码应该是,
expect {
timeout {puts timedout\n}
\\[1]: {puts matched\n}
}
您可以在 ]
前加一个反斜杠,如果这样会让您感觉良好,但事实并非如此
必要的。由于在
双引号字符串,右括号没有什么特别的发生。它代表自身并传递给 Expect
命令,然后在命令中将其解释为范围的末尾。
下一组示例将 [
的行为显示为以不同数量的反斜杠开头的模式。如果 [
没有以反斜杠作为前缀,则 Tcl
会将后面的内容解释为命令。对于这些示例,假设有一个名为 XY
的过程 returns 字符串 n*w
.
expect" [XY]" ; # matches n followed by anything
expect "\[XY]" ; # matches X or Y
expect "\[XY]" ; # matches n followed by anything followed by w
expect "\\[XY]" ; # matches [XYl
expect "\\[XY]" ; # matches \ followed by n followed ...
expect "\\\[XY]" ; # matches sequence of \ and X or Y
\[XY]
案例值得仔细研究。 Tcl
将第一个反斜杠解释为表示第二个是文字字符。 Tcl
然后生成 n*w
作为 XY 命令的结果。模式匹配器最终看到的是四个字符串 n*w
。模式匹配器以通常的方式对此进行解释。反斜杠表示 n
将按字面匹配(即使没有反斜杠,它也会匹配,因为 n 对于模式匹配器来说并不特殊)。
来源 : Exploring Expect
对我有用的模式:
-exact {[1]:}
-exact "\[1]:"
{\[1]:}
"\\[1]:"