javascript - 用于匹配 URL 的第一个实例的正则表达式
问题描述
假设我有一个字符串变量中的 HTML,htmlString
我想在 html 中找到一个 mp3 链接的第一个实例,并将该链接存储在一个变量中。
<html>
...
src="https://example.com/mp3s/2342344?id=24362456"
...
</html>
链接https://example.com/mp3s/2342344?id=24362456
将被提取。
注意 html 中有很多其他的 url,但我只想要这种格式的。
我怎么得到这个?
解决方案
虽然通常不建议使用正则表达式解析 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. ");
推荐阅读
- javascript - toggleClass jQuery 类赋值
- android - 在滚动视图中使用寻呼机进行缩放(类似于 instagram 的功能)
- android - 弹出窗口 Recyclerview 中的 Onclick 监听器
- arrays - PostgreSQL - 选择具有给定元素的数组的 JSON 行
- ffmpeg - ffmpeg 场景检测:只检查每第 n 帧?
- model-view-controller - 如何上传文件夹中的文件并将路径保存在数据库中?
- javascript - 从 HTML 模板调用异步函数(Retunes Observable)
- python - rpyc AsyncResultTimeout("结果过期")
- python - 如何使用 python 在云 pub/sub 中访问 grpc?
- c# - 如何在 ExecuteQueryDynamic 上的 LinqPad 上设置我的查询超时?