【问题标题】:Match beginning of a line and beginning of remain line匹配行首和剩余行首
【发布时间】:2022-10-05 08:50:46
【问题描述】:

我正在尝试提出与行首(时间戳)匹配的语法荧光笔,然后是剩余行的开始。 例如:

12:34:56.789 some1 text some2 other text
some3 text some4 other text

我需要捕获单词some,但前提是它位于文本的开头,忽略时间戳。所以在这个例子中他们是some1some3

{
  "$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json",
  "name": "my-output",
  "scopeName": "source.my_output",
  "patterns": [
    {
      "begin": "^(\\d{2}:\\d{2}:\\d{2}\\.\\d{3,}\\s)?",
      "end": "$",
      "beginCaptures":{
        "1": {"name": "my-output-date"}
      },
      "patterns": [
        
        {
          "match": "^(some\\d)",
          "captures":{
            "1": {"name": "my-output-red"}
          }
        }
      ]
    }
  ]
}

问题是行的开头可能以时间戳12:34:56.789 开头,因此在此示例中它仅捕获some3

如果我从正则表达式中删除 ^"match": "(some\\d)" 它会捕获所有 4 个单词。

vscode 是否提供将文本拆分为块并将每个块作为整个文本处理的能力(我们可以在块上使用^$)?

【问题讨论】:

  • 也许像这样"match": "^(?:\\d{2}:\\d{2}:\\d{2}\\.\\d{3,}\\s)?(some\\d)",
  • @Thefourthbird 这是我试图避免的一种方式,因为有几十个关键字,我试图在不重复的情况下让它不那么繁琐......
  • 那么也许您可以使用([^\\d\\s]+\\d) 以非数字后跟数字开始匹配?
  • 问题在于没有^,它可能会在字符串中间捕获,并且嵌套模式中似乎不允许^。例如,^.* 将不匹配任何内容,如果父模式匹配某些内容。

标签: regex visual-studio-code vscode-extensions tmlanguage


【解决方案1】:

最后,我找到了一个解决方案:使用G anchor - 最后一次匹配后的文本开头:

{
  "$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json",
  "name": "my-output",
  "scopeName": "source.my_output",
  "patterns": [
    {
      "begin": "^(\d{2}:\d{2}:\d{2}\.\d{3,}\s)?",
      "end": "$",
      "beginCaptures":{
        "1": {"name": "my-output-date"}
      },
      "patterns": [
        
        {
          "match": "\G(some\d)",
          "captures":{
            "1": {"name": "my-output-red"}
          }
        }
      ]
    }
  ]
}

但是,似乎有一个bug,如果前一行为空,它会跳过一行。目前,我的解决方法是将"end": "$" 正则表达式替换为:"end": "\r?\n"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-19
    • 1970-01-01
    • 2012-07-22
    • 2019-02-16
    • 1970-01-01
    相关资源
    最近更新 更多