鉴于此日志记录输出。我想匹配所有失败命令的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(就正则表达式而言,这是正确的,但不是期望的)
最佳答案
[\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/