首页 > 解决方案 > 是否可以在不破坏代码的情况下将 `if ... in` 和 `{` 保持在同一行?

问题描述

;  not work
Var := "Var"

if Var in Foo,Bar,Baz {
  MsgBox statement 1
  MsgBox statement 2
} else {
  MsgBox statement 3
  MsgBox statement 4
}

;  not work
Var := "Var"

if (Var in Foo,Bar,Baz) {
  MsgBox statement 1
  MsgBox statement 2
} else {
  MsgBox statement 3
  MsgBox statement 4
}

;  works, but the brace positions are inconsistent,
;    is it possible to keep `if ... in` and `{`
;    on the same line without breaking the code?
Var := "Var"

if Var in Foo,Bar,Baz
{
  MsgBox statement 1
  MsgBox statement 2
} else {
  MsgBox statement 3
  MsgBox statement 4
}

标签: if-statementconditional-statementsoperatorsautohotkeybrackets

解决方案


if ... in(docs)是遗留的,因此您不能将它包含在括号内,因为这将表示一个表达式。并且不能将括号放在同一行只是if ... in.

不幸的是,那里不是一个直接的现代替代品,所以你的要求是不可能的if ... in

但是,您可以放弃if ... in和遗留语法并使用例如正则表达式匹配速记运算符~=(文档),如下所示:

Var := "Var"

if (Var ~= "Foo|Bar|Baz") {
  MsgBox, % "nope"
} else if (Var ~= "Foo|Var|Baz") {
  MsgBox, % "yup"
}

根据user3419297的评论进行编辑:

如果您不锚定正则表达式模式,它也会匹配子字符串。如果您知道存在匹配子字符串的风险,请务必添加^$锚点,例如:

(Var ~= "^(Foo|Var|Baz)$")

推荐阅读