c# 匹配 img src ="*"类型 URLs 的正则表达式

标签 c# regex url pattern-matching

我在 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/

相关文章:

regex - 正则表达式获取长度为n的所有子串

php - 正则表达式和可分性

regex - 如何验证 pretty-config.xml 中的正则表达式

javascript - 将 URL 分解为其组成部分

javascript - Web Api 2 - 检查用户是否登录

c# - 更新面板内的 Page.Unload 事件

c# - 模拟页面生命周期从UI层抓取html

php - 缩短 URL GET 选项

ruby - Sinatra Url '/' 解释

重写与隐藏基类方法时的 C# 作用域差异