首页 > 文章列表 > 如何使用正则表达式从文本中提取 `` 标签的图片链接?

如何使用正则表达式从文本中提取 `` 标签的图片链接?

397 2025-03-11

如何使用正则表达式从文本中提取 `` 标签的图片链接?

使用正则获取 <> 之间的图片链接

在给定的文本中获取 <> 之间的图片链接,可以使用正则表达式来实现。以下提供了几种正则表达式解决方案:

// 匹配第一个 &lt;&gt; 之间的图片链接
const regex1 = /&lt;imgs*src="([^"]+)"s*/*&gt;/;

// 匹配所有 &lt;&gt; 之间的图片链接
const regex2 = /&lt;imgs*src="([^"]+)"[ss]*?&gt;/g;

使用正则表达式示例

const string = '<p>唉算阿萨德阿萨德阿萨德阿萨德阿萨德阿萨德阿萨德撒旦撒旦说道阿萨德说道阿萨德阿萨德阿萨德阿萨德阿萨德阿萨德阿萨德撒旦阿萨德撒旦阿萨德撒旦阿萨德是阿萨德&lt;img src="http://p9.pccoo.cn/webapp/20161230/2016123010375539992519_300_300.gif" /&gt;&lt;img src="http://p9.pccoo.cn/webapp/20161230/2016123010380668807050_300_300.gif" /&gt;</p>';

// 匹配第一个链接
console.log(regex1.exec(string)[1]);

// 匹配所有链接
console.log([...regex2.exec(string).slice(1)]);

输出结果

http://p9.pccoo.cn/webapp/20161230/2016123010375539992519_300_300.gif
[
  "http://p9.pccoo.cn/webapp/20161230/2016123010375539992519_300_300.gif",
  "http://p9.pccoo.cn/webapp/20161230/2016123010380668807050_300_300.gif"
]
来源:1730203058