【问题标题】:RegEx for matching the first instance of a URL用于匹配 URL 的第一个实例的正则表达式
【发布时间】:2019-05-04 16:41:09
【问题描述】:

假设我在字符串变量 htmlString 中有 HTML,我想在 html 中找到 mp3 链接的第一个实例,并将该链接存储在变量中。

<html>
...
src="https://example.com/mp3s/2342344?id=24362456"
...
</html>

将提取链接https://example.com/mp3s/2342344?id=24362456

请注意,html 中有很多其他 url,但我只想要这种格式的。

我如何得到这个?

【问题讨论】:

标签: javascript html regex parsing regex-group


【解决方案1】:

虽然通常不建议使用正则表达式解析 HTML,但如果您希望/必须获得第一个 mp3 URL,this expression 可能会帮助您设计表达式。

^(src=\x22(https:\/\/[a-z]+.com\/mp3s\/[0-9]+\?id=[0-9]+)\x22)[\s\S]*

为了安全起见,我为其添加了几个边界,您可以简单地将其从所需 URL 所在的第二个捕获组中删除或简化:

 (https:\/\/[a-z]+.com\/mp3s\/[0-9]+\?id=[0-9]+)

关键是要添加一个[\s\S]*,这样它就可以在捕获第一个 URL 后传递所有其他内容。

图表

这张图显示了它是如何工作的:

1000 万次性能基准的 JavaScript Demo

repeat = 10000000;

start = Date.now();

for (var i = repeat; i >= 0; i--) {
	var string = 'src=\"https://example.com/mp3s/2342344?id=24362456\" src=\"https://example.com/mp3s/08103480132984?id=0a0f8ad0f8\" src=\"https://example.com/mp3s/2342344?id=24362456\" href=\"https://example.com/mp3s/2342344?id=91847890\" src=\"https://example.com/mp3s/2342344?id0980184\"';
	var regex = /^(src=\x22(https:\/\/[a-z]+.com\/mp3s\/[0-9]+\?id=[0-9]+)\x22)[\s\S]*/g;

	var match = string.replace(regex, "$2");
}

end = Date.now() - start;

console.log(match + " is a match ? ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test. ? ");

【讨论】:

    猜你喜欢
    • 2014-06-30
    • 1970-01-01
    • 2019-12-21
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    相关资源
    最近更新 更多