我在 c# 中有一个正则表达式,我用它来匹配图像标签并提取 URL。我的代码在大多数情况下都有效。下面的代码会将所有相对图像 URL“修复”为绝对 URL。
问题是正则表达式不会匹配以下内容:
<img height="150" width="202" alt="" src="../Image%20Files/Koala.jpg" style="border: 0px solid black; float: right;">
例如它匹配这个就好了
<img height="147" width="197" alt="" src="../Handlers/SignatureImage.ashx?cid=5" style="border: 0px solid black;">
任何关于如何使其匹配的想法都会很棒。我认为问题在于百分比,但我可能错了。
Regex rxImages = new Regex(" src=\"([^\"]*)\"", RegexOptions.IgnoreCase & RegexOptions.IgnorePatternWhitespace);
mc = rxImages.Matches(html);
if (mc.Count > 0)
{
Match m = mc[0];
string relitiveURL = html.Substring(m.Index + 6, m.Length - 7);
if (relitiveURL.Substring(0, 4) != "http")
{
Uri absoluteUri = new Uri(baseUri, relitiveURL);
ret += html.Substring(0, m.Index + 5);
ret += absoluteUri.ToString();
ret += html.Substring(m.Index + m.Length - 1, html.Length - (m.Index + m.Length - 1));
ret = convertToAbsolute(URL, ret);
}
}
最佳答案
以这种方式使用 RegEx 解析图像是个坏主意。参见 here为了很好地说明原因。
您可以使用 HTML 解析器,例如 HTML Agility Pack解析 HTML 并使用 XPath 语法查询它。
关于c# 匹配 img src ="*"类型 URLs 的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3680067/