You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求提供可提取img标签中src属性值的正则表达式

Regex to Extract src Attributes from <img> Tags

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 i flag (e.g., in JavaScript: /<img[^>]*src\s*=\s*["']?([^"'>]+)["']?[^>]*>/gi) to match <img>, <IMG>, <iMg>, etc.
  • Global Matching: Add the g flag if you need to extract all src values from a multi-tag string.
  • Pattern Breakdown:
    • <img : Matches the start of any case-variant image tag
    • [^>]* : Skips any characters (other than >) before the src attribute
    • src\s*=\s* : Matches the src attribute with optional whitespace around the equals sign
    • ["']? : Optional opening quote (supports both single and double quotes)
    • ([^"'>]+) : Capturing group that extracts the actual src value (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:00:49