我有点困惑我的输入字符串是“ foo/1”我的动机是将 foo 设置为变量并对其进行正则表达式:
set line " foo/1"
set a foo
regexp "\s$a" $line does not work
Run Code Online (Sandbox Code Playgroud)
我还注意到,只有当我使用花括号并给出确切的字符串大括号时,它才有效
regexp {\sfoo} $line works
regexp "\sfoo" $line doesnt work
Run Code Online (Sandbox Code Playgroud)
有人可以解释为什么吗?谢谢
快速回答:
"\\s"=={\s}
长答案:
在 Tcl 中,如果您键入一个字符串,使用""for 将其括起来,则内部的所有内容将首先被评估,然后用作字符串。这意味着\s被评估(解释)为转义字符,而不是两个字符。
如果你想在字符串\中输入字符,""你也必须对其进行转义:\\。在你的情况下,你必须输入"\\sfoo".
如果是{}封闭的字符串,它们总是被引用,不需要重复的反斜杠。
如果您想在字符串中使用变量或内联命令,则使用""是很好的,例如:
puts "The value $var and the command result: [someCommand $arg]"
Run Code Online (Sandbox Code Playgroud)
上面将评估$varand[someCommand $arg]并将它们放入字符串中。
如果您使用了大括号,例如:
puts {The value $var and the command result: [someCommand $arg]}
Run Code Online (Sandbox Code Playgroud)
该字符串将不会被评估。它将包含所有$和[字符,就像您键入它们一样。