简体   繁体   English

html图像字符串上的正则表达式

[英]Regex expression on html image string

I'm struggling with completing a regex expression, and it would be greatly appreciated if someone could help.我正在努力完成正则表达式,如果有人能提供帮助,我们将不胜感激。

I'm trying to get the source of the image from this HTML div tag我试图从这个 HTML div 标签中获取图像的来源

<div class="preview item"><img alt=""
    sizes="(max-width: 440px) 320px"
    src= "https://m.testlink.com/test/zx320y230c_4130512.jpg"
    srcset= "https://m.testlink.com/test/zx320y230c_4130512.jpg 320w, https://m.testlink.com/test/zx640y460c_4130512.jpg 640w"></div>

Here is what I have so far:这是我到目前为止所拥有的:

const imgRegX = /<div class="?preview item"?[^>]*>\s*<img alt="?" sizes= "?"/g;

For some reason when I add the sizes it breaks.出于某种原因,当我添加尺寸时它会中断。

I also assume this is how the src regex would look like, but so far I can't figure out the sizes.我还假设这就是 src 正则表达式的样子,但到目前为止我无法弄清楚大小。

src="?([^"\s]+)/

You can use elements to get this information from the document without using a RegEx.您可以使用元素从文档中获取此信息,而无需使用 RegEx。 For example, the below extracts the src attribute for all images that are children of the "preview" div.例如,下面为“预览”div 的所有子图像提取src属性。

 const previews = document.getElementsByClassName('preview'); for (let item of previews) { var images = item.getElementsByTagName('img'); for (let img of images) { console.log('Source:', img.src); } }
 <div class="preview item"><img alt="" sizes="(max-width: 440px) 320px" src= "https://m.testlink.com/test/zx320y230c_4130512.jpg" srcset= "https://m.testlink.com/test/zx320y230c_4130512.jpg 320w, https://m.testlink.com/test/zx640y460c_4130512.jpg 640w"></div>

RegEx Problem正则表达式问题

Your RegEx problem is caused by an unexpected space here: src= " There is a space before the quote, which means it no longer matches your expression. The below screenshot is taken from RegEx101 .您的 RegEx 问题是由此处的意外空格引起的: src= "引号前有空格,这意味着它不再与您的表达式匹配。以下屏幕截图来自RegEx101

You could cater for the whitespace after the = sign in your RegEx:您可以在 RegEx 中处理=符号后的空格:

src=\s"?([^"\s]+)

正则表达式测试

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

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