用于捕获图像 src 属性的正则表达式
Regex for capturing image src attribute
我正在尝试提取双引号内的所有图片链接。
我可以使用
获取引号内的文本
/"([^"]*)"/
但我只想获取与以下模式匹配的那些值
"https://text/text/.../text.jpg?text=text&text=..."
(...代表相似值)
我怎样才能做到这一点?
/['"]+/g
应该可以
let urlStr= "https://text/text/........./text.jpg?text=text&text=.......';
console.log(urlStr.replace(/['"]+/g, ''));
你的试用还不错。这里,我们也可以用一个简单的左右"
边界,收集中间的数据:
"(.+?)"
Demo
const regex = /"(.+?)"/gm;
const str = `"https://text/text/........./text<b>.jpg?text=text&text=.......</b>"`;
const subst = ``;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
如果 url 必须以 http 和可选的 s 开头,并且它必须包含 .jpg
,您可能会使您的模式更具体一些:
"(https?:\/\/[^"\s]+\/\S+?\.jpg[^"\s]*)"
"(
匹配开头"并开始捕获组
https?:\/\/
将 http 与可选的 s 和 :// 匹配
[^"\s]+
不匹配 " 或空白字符
\/\S+?\.jpg
匹配一个正斜杠,1+次非空白字符非贪婪和.jpg
[^"\s]*
匹配 0+ 次非空格字符或 " 以匹配文件扩展名后面的内容
)"
关闭捕获组并匹配关闭 "
let pattern = /"(https?:\/\/[^"\s]+\/\S+?\.jpg[^"\s]*)"/;
[
'"https://text/text/.../text.jpg?text=text&text=..."',
'"https://text/text/.../text.jpg?t&ext=text&text=..."',
'"https://text/text/.../text.jpg?text=text"'
].forEach(s => console.log(s.match(pattern)[1]))
我正在尝试提取双引号内的所有图片链接。
我可以使用
获取引号内的文本/"([^"]*)"/
但我只想获取与以下模式匹配的那些值
"https://text/text/.../text.jpg?text=text&text=..."
(...代表相似值)
我怎样才能做到这一点?
/['"]+/g
应该可以
let urlStr= "https://text/text/........./text.jpg?text=text&text=.......';
console.log(urlStr.replace(/['"]+/g, ''));
你的试用还不错。这里,我们也可以用一个简单的左右"
边界,收集中间的数据:
"(.+?)"
Demo
const regex = /"(.+?)"/gm;
const str = `"https://text/text/........./text<b>.jpg?text=text&text=.......</b>"`;
const subst = ``;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log('Substitution result: ', result);
如果 url 必须以 http 和可选的 s 开头,并且它必须包含 .jpg
,您可能会使您的模式更具体一些:
"(https?:\/\/[^"\s]+\/\S+?\.jpg[^"\s]*)"
"(
匹配开头"并开始捕获组https?:\/\/
将 http 与可选的 s 和 :// 匹配
[^"\s]+
不匹配 " 或空白字符\/\S+?\.jpg
匹配一个正斜杠,1+次非空白字符非贪婪和.jpg[^"\s]*
匹配 0+ 次非空格字符或 " 以匹配文件扩展名后面的内容
)"
关闭捕获组并匹配关闭 "
let pattern = /"(https?:\/\/[^"\s]+\/\S+?\.jpg[^"\s]*)"/;
[
'"https://text/text/.../text.jpg?text=text&text=..."',
'"https://text/text/.../text.jpg?t&ext=text&text=..."',
'"https://text/text/.../text.jpg?text=text"'
].forEach(s => console.log(s.match(pattern)[1]))