问题描述
查看用户定义片段的vscode文档,它会出现使用正则表达式转换,您可以执行 if/else 条件.
Looking at the vscode documentation for user defined snippets, it would appear that using the regex transform, you can do if/else conditions.
但是,我似乎找不到任何这样的例子,而且我正在努力理解仅基于 BNF 的正确语法.
However, I can't seem to find any examples of this and I'm struggling to understand the correct syntax based on the BNF alone.
有人可以解释一下这个语法吗?
Can someone explain the syntax for this?
例如
假设我有一个这样的片段:
Lets say I have a snippet like this:
"body": [
"let color = '${1|white,black|}';",
"let hex = '${???}';"
]
如果color==white
,我希望十六进制输出#fff
,否则如果黑色#000
.
If color==white
, I want hex to output #fff
, otherwise if black #000
.
推荐答案
这有效:
"color conditional": {
"prefix": "_hex",
"body": [
"let color = '${1};",
"let hex = '${1/(white)|(black)|(red)/${1:+#fff}${2:+#000}${3:+#f00}/}';" //works
],
"description": "conditional color"
},
但是,一旦我尝试使用默认占位符和选项,例如
However, as soon as I try it with default placeholders and choices, like
"let color = '${1|white,black|}';", // does not work
显然,您不能对默认占位符值进行片段转换.请参阅占位符值问题的转换
Apparently, you cannot do snippet transforms on default placeholder values. See transforms on placeholder values issues
我使用了更简单的 if
转换样式,所以在这里:
I used the simpler if
transform style, so here:
${1/(white)|(black)|(red)/${1:+#fff}${2:+#000}${3:+#f00}
如果有第 1 组 $[1}
在这种情况下 white
然后用 #fff
替换第 1 组,如果第 2 组(black)
替换为 #000
等
if there is a group 1 $[1}
in this case white
then replace that group 1 with #fff
and if group 2 (black)
replace with #000
, etc.
你可以把它变成一个 if/else
(white)
或者不是很容易.
You could make it just an if/else
(white)
or not pretty easily.
"let hex = '${1/(white)/${1:?#fff:#000}/}';" // any non-`white` entry will print `#000`.
${1:?
=> 如果组 1 (white)
打印 #fff
,否则打印 #000代码>
${1:?
=> if group 1 (white)
print #fff
, else print #000
vscode 文档对这些条件替换不是很有帮助,如果您对它们的语法有更多疑问,请告诉我.
The vscode docs are not very helpful on these conditional replacements, if you have more questions on their syntax, let me know.
这篇关于vscode 用户定义代码段中的 if/else 条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!