Regex-匹配URL,但不匹配堆栈跟踪中的前一行数字



因此,我正在编写一个ASP.Net应用程序,该应用程序将轮询用于其他应用程序的日志数据库,并以易读的方式显示日志。我已经完成了基本功能,但我想"链接"StackTrace中出现的URL,这样点击它们就会打开相关文件。

at initialiseProducts (http://localhost:51940/POS/POS.js:520:22)
at Object.success (http://localhost:51940/POS/POS.js:67:17)
at i (http://localhost:51940/jquery-3.2.0.min.js:2:28017)
at Object.fireWith [as resolveWith] (http://localhost:51940/jquery-3.2.0.min.js:2:28783)
at A (http://localhost:51940/jquery-3.2.0.min.js:4:14017)
at XMLHttpRequest. (http://localhost:51940/jquery-3.2.0.min.js:4:16305)

在StackOverflow的一些搜索之后,我发现了一个Regex,它将检测我的URL而不会发出

/(b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|])/ig

然而,它也将与URL末尾的行号和列号:520:22相匹配,这意味着单击链接时无法找到文件。

是否可以修改此Regex以忽略每个URL末尾的行号和列号?

这是regex的一个修改版本,您可以从捕获中排除行号和列号,如下所示:

(b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*):d+:d+

现场演示

组1包含您的URL。

const regex = /(b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*?):d+:d+/ig;
const str = `at initialiseProducts (http://localhost:51940/POS/POS.js:520:22)
at Object.success (http://localhost:51940/POS/POS.js:67:17)
at i (http://localhost:51940/jquery-3.2.0.min.js:2:28017)
at Object.fireWith [as resolveWith] (http://localhost:51940/jquery-3.2.0.min.js:2:28783)
at A (http://localhost:51940/jquery-3.2.0.min.js:4:14017)
at XMLHttpRequest. (http://localhost:51940/jquery-3.2.0.min.js:4:16305)`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}

// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}

最新更新