首页 > 解决方案 > 用于匹配 URL 的第一个实例的正则表达式

问题描述

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

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

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

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

我怎么得到这个?

标签: javascripthtmlregexparsingregex-group

解决方案


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

^(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.  ");


推荐阅读