如何从此日志记录输出中找到最里面的失败模式

时间:2018-07-04 03:37:25

标签: javascript regex

给出此日志记录输出。我想匹配所有失败命令中的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

但这还不够好。勉强的量词与最里面匹配的third.command 不匹配。而是匹配匹配first.command(就正则表达式而言,这是正确的,但不希望如此)

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

1 个答案:

答案 0 :(得分:1)

[\s\S]+会贪婪地匹配任何字符序列,包括换行符,但是您只想搜索到遇到FailDone的地方。由于Some Text行总是正好长一行,因此(在命令之后)通过匹配 [\s\S](换行符)和后一行字符来利用此优势,然后是另一个[\s\S]+(换行符),然后是Fail

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]);
}

如果使用后向(较新,支持较少),则更简单:

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));