代码之家  ›  专栏  ›  技术社区  ›  gawicks

如何从这个日志输出中找到最里面的失败模式

  •  0
  • gawicks  · 技术社区  · 6 年前

    给出了这个日志输出。我想匹配 path/to/*.command 在所有失败的命令中。在本例中是第三个和第四个命令。

        Starting.. path/to/first.command
          Some Text..
        Done
    
        Starting.. other/path/to/second.command
          Some Other Text..
        Done
    
        Starting.. other/path/to/third.command
          Some Text..
        Fail
    
        Starting.. other/path/to/forth.command
          Some Other Text..
        Fail
    

    这就是我想到的 Starting.. (.+\.command)[\s\S]+?Fail

    但还不够好。不情愿的量词 与最内部的match third.command不匹配 。但它与包含first.command的匹配(就regex而言,这是正确的,但不需要)

    演示: https://regex101.com/r/fl3eaz/1

    1 回复  |  直到 6 年前
        1
  •  1
  •   CertainPerformance    6 年前

    [\s\S]+ 将贪婪地匹配任何字符序列,包括换行符,但您只希望搜索到 Fail Done 遇到。因为 Some Text 行总是只有一行,通过(在命令之后)匹配 单一的 [\s\S] (换行符),后跟一行字符,然后是另一行字符 [s s] + (换行),后跟 失败 .

    const input = `
        Starting.. path/to/first.command
          Some Text..
        Done
    
        Starting.. other/path/to/second.command
          Some Other Text..
        Done
    
        Starting.. other/path/to/third.command
          Some Text..
        Fail
    
        Starting.. other/path/to/forth.command
          Some Other Text..
        Fail
        `;
    const re = /Starting\.\. (.+\.command)[\s\S].+[\s\S] +Fail/g;
    let match;
    while (match = re.exec(input)) {
      console.log(match[1]);
    }

    如果使用(更新的,不受支持的)lookbehind,则更简单:

    const input = `
        Starting.. path/to/first.command
          Some Text..
        Done
    
        Starting.. other/path/to/second.command
          Some Other Text..
        Done
    
        Starting.. other/path/to/third.command
          Some Text..
        Fail
    
        Starting.. other/path/to/forth.command
          Some Other Text..
        Fail
        `;
    const re = /(?<=Starting\.\. +).+\.command(?=[\s\S].+[\s\S] +Fail)/g;
    console.log(input.match(re));