简体   繁体   English

用于捕获图像src属性的正则表达式

[英]Regex for capturing image src attribute

I'm trying to extract all image links within double quotations. 我正在尝试提取双引号内的所有图像链接。

I'm able to get text within quotes by using 我可以通过使用引号内的文本

/"([^"]*)"/

but I want to get only those values which match following pattern 但我只想获得与以下模式匹配的那些值

"https://text/text/.../text.jpg?text=text&text=..."

(... Represents similar values) (...代表相似的值)

How can I achieve this? 我该如何实现?

If the url has to start with http and optional s and it has to contain .jpg you might make your pattern a bit more specific: 如果网址必须以http和可选的s开头并且必须包含.jpg ,则可以使模式更具体:

"(https?:\/\/[^"\s]+\/\S+?\.jpg[^"\s]*)"
  • "( Match opening " and start capturing group "(比赛开始”并开始抓捕小组
    • https?:\\/\\/ Match http with optional s and :// https?:\\/\\/ http与可选的s和://匹配
    • [^"\\s]+ Match not " or a whitespace char [^"\\s]+不匹配”或空格字符
    • \\/\\S+?\\.jpg Match a forward slash, 1+ times a non whitespace char non greedy and .jpg \\/\\S+?\\.jpg匹配正斜杠,非空格字符非贪婪和.jpg的1+倍
    • [^"\\s]* Match 0+ times not a whitespace char or " to match what follows the file extension [^"\\s]*匹配0+次不是空格字符或”,以匹配文件扩展名后面的内容
  • )" Close capturing group and match closing " )"关闭捕获组并关闭比赛”

Regex demo 正则表达式演示

 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])) 

/['"]+/g 

should work 应该管用

let urlStr= "https://text/text/........./text.jpg?text=text&text=.......';
console.log(urlStr.replace(/['"]+/g, ''));

Your trial is pretty good. 您的审判很好。 Here, we can also use a simple left and right " boundary and collect the data in between: 在这里,我们也可以用一个简单的左,右"边界与收集的数据:

"(.+?)"

Demo 演示版

 const regex = /"(.+?)"/gm; const str = `"https://text/text/........./text<b>.jpg?text=text&text=.......</b>"`; const subst = `$1`; // The substituted value will be contained in the result variable const result = str.replace(regex, subst); console.log('Substitution result: ', result); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM