请求提供可提取img标签中src属性值的正则表达式
Here's a robust regex pattern that handles your requirements—including case-insensitive <img> tags, varying positions of the src attribute, and quoted (single/double) or unquoted values:
<img[^>]*src\s*=\s*["']?([^"'>]+)["']?[^>]*>
Key Details:
- Case Insensitivity: Use the
iflag (e.g., in JavaScript:/<img[^>]*src\s*=\s*["']?([^"'>]+)["']?[^>]*>/gi) to match<img>,<IMG>,<iMg>, etc. - Global Matching: Add the
gflag if you need to extract allsrcvalues from a multi-tag string. - Pattern Breakdown:
<img: Matches the start of any case-variant image tag[^>]*: Skips any characters (other than>) before thesrcattributesrc\s*=\s*: Matches thesrcattribute with optional whitespace around the equals sign["']?: Optional opening quote (supports both single and double quotes)([^"'>]+): Capturing group that extracts the actualsrcvalue (stops at the first closing quote or end of the tag)["']?: Optional closing quote[^>]*>: Skips any remaining characters in the tag until the closing>
Example Usage (JavaScript):
const html = ` <div style="TEXT-ALIGN: center"><img src="Images/17/0000894189/0000894189-17-005831/image00003.jpg"></div> <div style="TEXT-ALIGN: justify"><iMg style="HEIGHT: 63px; WIDTH: 289px" src="Images/17/0000894189/0000894189-17-005831/image0.jpg"></div> `; const regex = /<img[^>]*src\s*=\s*["']?([^"'>]+)["']?[^>]*>/gi; let match; const srcValues = []; while ((match = regex.exec(html)) !== null) { srcValues.push(match[1]); } console.log(srcValues); // Output: ["Images/17/0000894189/0000894189-17-005831/image00003.jpg", "Images/17/0000894189/0000894189-17-005831/image0.jpg"]
Notes:
While regex works great for simple cases like yours, for complex HTML parsing (e.g., nested tags, comments, or malformed markup), consider using a dedicated HTML parser (like DOMParser in browsers or cheerio in Node.js). Regex isn't ideal for full HTML parsing, but it's perfect for your specific use case.
内容的提问来源于stack exchange,提问作者user423574
相关产品推荐
相关产品推荐

