正则表达式在 VS Code 中看后面?

Regex look behind in VS Code?

我正在 VS Code 中进行语法扩展,但我很难了解正则表达式模式。给定以下字符串,我只想在 return cmp 前面加上 @fmt(

@fmt(cmp,foo)

我在另一个编辑器中使用的匹配字符串是这样的:

(?<=[@|©](fmt)\()(\w+)

但是,这在 VS Code 中不起作用,当我进行正则表达式搜索时,它会返回错误,指出它不是有效的表达式。玩弄它,问题是 <= 个字符,表示后面的样子。

搜索 VS Code 网站 return 没有任何类型的正则表达式参考指南。搜索 Stack Overflow 得出 this question,其中指出 Visual Studio 具有独特的正则表达式定义。不幸的是,该问题中给出的示例在 VS Code 中不起作用。

有人知道如何在 VS Code 中查看正则表达式吗?或者至少知道 VS Code 的正则表达式文档位于何处?

我担心这是不可能的,因为根据 Stack Overflow reference look behinds aren't supported in JavaScript. There is another question 显示如何在 JavaScript 函数中模仿后视,但我不知道是否可以扩展语言具有用户定义函数的 VS 代码。如果有人知道该怎么做,并且可以指出我的方向,那也是一个可以接受的解决方法。

在 VS Code 中向前看和向后看。下载一些现有的语言插件并查看它们的规则,以了解必须如何制定。这是我的 ANTLR 语法扩展的一部分:

{
  "name": "meta.rule.parser.antlr",
  "begin": "[[:lower:]][[:alnum:]_]*(?=.*?:)",
  "beginCaptures": {
    "0": { "name": "entity.name.function.parser.antlr" }
  },
  "end": "(?<=;)",
  "patterns": [
    {
      "name": "variable.other",
      "match": "\[.*?\]"
    },
    {
      "name": "keyword.other.antlr",
      "match": "\b(returns|locals)\b"
    },
    {
      "name": "keyword.other.antlr",
      "match": "@\w+"
    },
    {
      "name": "entity.other.rule.option",
      "match":" <.*?>"
    },
    {
      "name": "variable.other.antlr",
      "match": "\w+\s*="
    },
    {
      "name": "entity.name.tag.antlr",
      "match": "#.*"
    },

    { "include": "#comments" },
    { "include": "#strings" },
    { "include": "#lexer-rule-reference" },
    { "include": "#parser-rule-reference" },
    { "include": "#predicate" },
    { "include": "#action" },
    { "include": "#wildcard-regexp" },
    { "include": "#regexp-parts" },
    { "include": "#options-list" }

  ]
}

最后一场比赛使用了后视模式。还要记住,您可以嵌套模式,即您可以为更大的结构(例如整个函数)定义 begin/end,然后将其部分与子模式匹配(并分配单独的样式)。这就是为什么您通常不需要查看 ahead/behind 的原因,因为您知道自己在某个代码块中。

对于上面的模式:(\w+) 部分应该是后视模式的一部分吗?如果是这样,它应该在最后一个右括号之前。

更新

Visual Studio 代码 v.1.31.0 及更高版本支持正则表达式回顾,请参阅


Visual Studio 代码使用 ECMAScript 5 中指定的 JavaScript 的正则表达式,它不支持向后看 (https://github.com/Microsoft/vscode/issues/8635)。

如果您正在查找和替换(感谢 cyborgx37),您可以尝试以下解决方法:

搜索表达式:

(lookbehind_expression_)text_to_replace

替换表达式:

replacement_text

给定输入:

lookbehind_expression_text_to_replace

输出将是:

lookbehind_expression_replacement_text

现在可以不受任何限制地使用infinite-width lookahead and lookbehind Visual Studio Code v.1.31.0 release.

见证明:

和另一个(使用 (?<=@fmt\([^()]*)\w+ 模式,注意后视中的 *):

参见 Github [VSCode 1.31] ES2018 RegExp lookbehind assertions are now supported #68004 issue:

As a result of moving to Electron 3.0, RegExp lookbehind assertions are now supported, since they’re supported since Chromium 62 and Node 8.10.0, and Electron 3.0 uses Chromium 66 and Node 10.2.0, so they’re now supported, but the release notes don’t mention that lookbehind assertions are now supported.

VS Code 开发人员 confirm that it is true 他们 "forgot to mention it in the release notes".