gpt4 book ai didi

javascript - RegEx 捕获尖括号(或管道)之间的 URL

转载 作者:行者123 更新时间:2023-11-29 16:08:26 25 4
gpt4 key购买 nike

考虑以下 URL:

  • <http://www.google.com>
  • <http://www.google.com|www.google.com>
  • <http://google.com|google.com>

我试图找出一个正则表达式来捕获 < 之后的 URL直到 |或者 >

我试过了 URL.match(/<([^>|\|]+)/g)但它总是捕获第一个 <

所需的输出很简单:http://www.google.com

最佳答案

RegEx 是正确的。 String#match将返回完整的匹配集。您需要提取第一个捕获的组。

使用RegExp#exec获取 URL。

var str = `<http://www.google.com>
<http://www.google.com|www.google.com>
<http://google.com|google.com>`;

var regex = /<([^>|\|]+)/g;

var urls = [];
while(match = regex.exec(str)) {
urls.push(match[1]); // Get first captured group, and push in array
}

console.log(urls);
document.body.innerHTML = '<pre>' + JSON.stringify(urls, 0, 4) + '</pre>';


您还可以使用 String#match如下:

str.match(/[^<>|\s]+/g)

var str = `<http://www.google.com>
<http://www.google.com|www.google.com>
<http://google.com|google.com>`;
var urls = str.match(/[^<>|\s]+/g);

console.log(urls);
document.body.innerHTML = '<pre>' + JSON.stringify(urls, 0, 4) + '</pre>';

关于javascript - RegEx 捕获尖括号(或管道)之间的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34840041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com