【问题标题】:Extract all images from html string using Regex使用正则表达式从 html 字符串中提取所有图像
【发布时间】:2021-08-19 10:18:05
【问题描述】:

我正在尝试使用正则表达式从 html 字符串中提取所有图像源。由于几个原因,我不能使用 HTML Agitility Pack。

我需要从看起来像这样的字符串中提取“gfx/image.png”

<table cellpadding="0" cellspacing="0"  border="0" style="height:350px; margin:0; background: url('gfx/image.jpg') no-repeat;">
<table cellpadding="0" cellspacing="0" border="0" background="gfx/image.jpg" style=" width:700px; height:250px; "><tr><td valign="middle">

【问题讨论】:

标签: c# regex


【解决方案1】:

你可以使用这个正则表达式:(['"])([^'"]+\.jpg)\1 然后获取 Groups[2],此代码运行良好:

var str = @"<table cellpadding=""0"" cellspacing=""0""  border=""0"" style=""height:350px; margin:0; background: url('gfx/image.jpg') no-repeat;"">
<table cellpadding=""0"" cellspacing=""0"" border=""0"" background=""gfx/image.jpg"" style="" width:700px; height:250px; ""><tr><td valign=""middle"">";
var regex = new Regex(@"(['""])([^'""]+\.jpg)\1");
var match = regex.Match(str);
while (match.Success)
{
    Console.WriteLine(match.Groups[2].Value);
    match = match.NextMatch();
}

【讨论】:

  • 如果您需要所有图片,正则表达式可以更改为:(['"])([^'"]+\.(jpg|png|bmp|gif))\1
  • 如果只是为了提取图像,正则表达式是轻量级的方式,制表符或换行符,你可以像(['"])([^'"\s]+\.(jpg|png|bmp|gif))\1这样改变正则​​表达式,这个正则表达式可以自动识别''和'',你没看到['"] 和 \1 ?
猜你喜欢
  • 2017-10-02
  • 1970-01-01
  • 1970-01-01
  • 2012-04-27
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
  • 1970-01-01
  • 2019-06-05
相关资源
最近更新 更多