gpt4 book ai didi

regex - 如何使用 "!"作为注释指示符,同时在语言语法高亮中使用 NOT 运算符?

转载 作者:行者123 更新时间:2023-12-02 19:59:05 25 4
gpt4 key购买 nike

我正在使用 VScode 并创建自己的语言扩展来突出显示语法,其中我需要使用正则表达式来查找注释。

基本规则是 ! 之后的所有内容都是注释,但是有一个特殊情况。当 ! 位于 eval() 命令内时,表示 NOT。

例如,我的一些代码如下所示:

if condition=(eval(!DB_EXIST)) ! this is a comment
(eval( !DB_UPDATED && !DB_EXIST)) !---"!" inside eval() means NOT
!this is another comment
<some commands> ! this is also a comment

第 1 行和第 2 行中的 !DB_EXIST 不应被解释为注释,并且 ! 后面将跟一个非空格。

注释中的空格并不重要。

"comments": {
"patterns" [{
"match":"regex1",
"name":"comment"
}]
},
"operator": {
"patterns" [{
"match":"regex2",
"name":"keyword.operator.NOT"
}]
},

我应该使用哪种正则表达式 1 和 2 来为注释显示不同的颜色,而不是?

我不擅长写扩展,所以如果有更好的方法来完成这项工作,我将非常感激。谢谢!

更新

@Gama11 帮助了我,但我没有完全涵盖代码示例中的所有情况。“!”之后的任何非空格也应该是注释,只要“!”不在 eval() 内部。

最佳答案

这是一种方法:

{
"$schema": "https://raw.githubusercontent.com/Septh/tmlanguage/master/tmLanguage.schema.json",
"scopeName": "source.abc",
"patterns": [
{
"begin": "(eval)\\(",
"end": "\\)",
"captures": {
"1": {
"name": "entity.name.function"
}
},
"patterns": [
{
"include": "#parens"
},
{
"match": "!",
"name": "keyword"
}
]
},
{
"match": "!.*?$",
"name": "comment"
}
],
"repository": {
"parens": {
"begin": "\\(",
"end": "\\)",
"patterns": [
{
"include": "#parens"
}
]
}
}
}

我们将模式设置为非注释 !首先,因为它更具体,并且应该优先于另一个。另外,我使用了 "keyword"范围而不是更合适的"keyword.operator.NOT"所以它实际上在屏幕截图中显示了不同的颜色。

第一个正则表达式是 begin -end模式,它允许我们仅对这两个匹配之间的文本应用模式(在本例中是在eval()调用内)。当我们这样做时,我们不妨强调 eval作为 entity.name.function 的函数范围。

如果我们在eval()内,我们允许两种模式:

  • 递归begin -end模式(包括自身)来平衡括号(您可能有类似 eval(foo() + !bar()) 的东西,并且 ) 中的 foo() 不应该结束 eval -模式)
  • !我们首先感兴趣的运算符

第二个正则表达式简单地匹配 ! ,然后是任何内容 ( .*? ),直到行尾 ( $ )。

一般来说,我强烈建议使用像 regex101.com 这样的工具用于使用 TM Grammar 文件的正则表达式。比在 VSCode 本身中进行迭代要容易得多,因为您可以获得即时反馈。

关于regex - 如何使用 "!"作为注释指示符,同时在语言语法高亮中使用 NOT 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56279964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com