if-statement - 是否可以在不破坏代码的情况下将 `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 ... 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)$")
推荐阅读
- c++ - 在 Visual Studio 2019 C_language 中不起作用 fopen_s(&file, "filename", mode)
- android - 单击 Tablayout 中的选项卡时移动到 RecylerView 中的特定位置
- typescript - 如何在 TypeScript 中创建全局可用的接口/类型?
- android - Cardview 与使用回收站视图和线性布局的父级不匹配
- reactjs - React,在网络上打开手机摄像头
- sql - 将用户 ID 从文本字段解析到新列
- javascript - React recursion with map 不适用于嵌套元素
- javascript - React JS:相同 JSON 数据的两个过滤器
- r - 将 dsG 变成 dsC 矩阵
- google-cloud-platform - 有没有办法在 GCP 云存储中托管一个公共静态网站并使用用户名和密码保护它?