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

标签 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

这就是我想出的开始..(.+\.command)[\s\S]+?失败

但这还不够好。不情愿的量词与最内部的匹配third.command 不匹配。但它匹配封闭的first.command(就正则表达式而言,这是正确的,但不是期望的)

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

最佳答案

[\s\S]+将贪婪地匹配任何字符序列,包括换行符,但您只想搜索到 Fail 所在的位置。或Done遇到。因为Some Text行始终恰好是一行长,通过(在命令之后)匹配 single [\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]);
}

如果您使用(较新、支持较少的)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));

关于javascript - 如何从此日志输出中找到最里面的失败模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51165394/

相关文章:

javascript - 在选项中添加图像

javascript - 使用 JavaScript 将字符串与正则表达式匹配

Java正则表达式创建问题

javascript - 如何在 RegExp 中创建 OR 条件?

正则表达式获取三位数的特定数字

javascript - 使用带参数的函数更改全局变量 Javascript

javascript - jQuery/JS : Looking for a way to animate a cube in 3D perspective

javascript - 在静态(词法)作用域中,变量/声明标识符何时绑定(bind)?

javascript - three.js PointCloud 中的可点击粒子

javascript - 正则表达式匹配其边界