如何使用正则或JS字符串方法从指定URL中提取目标PDF链接?
提取PDF链接的实现方法
完全可以实现,以下是两种可直接运行的JavaScript实现方案:
方案1:URI解码+后缀匹配法
先对源URL做URI解码还原编码字符,再直接匹配目标PDF路径即可:
const sourceUrl = 'https://s3.ap-south-1.amazonaws.com/abc-test-bucket/test-service/https%3A/%2Fabc-test-bucket.s3.ap-south-1.amazonaws.com/test-Service/0022JUN_29O00190_126072.pdf'; // 解码URL里的转义字符 const decodedStr = decodeURIComponent(sourceUrl); // 匹配以目标桶域名开头、.pdf结尾的完整路径 const targetPdf = decodedStr.match(/abc-test-bucket\.s3\.ap-south-1\.amazonaws\.com.*\.pdf/)[0]; console.log(targetPdf); // 输出结果:abc-test-bucket.s3.ap-south-1.amazonaws.com/test-Service/0022JUN_29O00190_126072.pdf
方案2:直接正则提取法
不需要提前解码,直接匹配编码后的目标片段再做解码,适合源URL结构固定的场景:
const sourceUrl = 'https://s3.ap-south-1.amazonaws.com/abc-test-bucket/test-service/https%3A/%2Fabc-test-bucket.s3.ap-south-1.amazonaws.com/test-Service/0022JUN_29O00190_126072.pdf'; const matchRule = /%2F(abc-test-bucket\.s3\.ap-south-1\.amazonaws\.com.*?\.pdf)/; const matchResult = sourceUrl.match(matchRule); const targetPdf = matchResult ? decodeURIComponent(matchResult[1]) : ''; console.log(targetPdf); // 输出结果:abc-test-bucket.s3.ap-south-1.amazonaws.com/test-Service/0022JUN_29O00190_126072.pdf
注意:如果后续桶名、区域有变动,只需要调整正则里对应前缀的匹配规则即可正常使用。
内容的提问来源于stack exchange,提问作者Hithesh kumar
相关产品推荐
相关产品推荐

