代码之家  ›  专栏  ›  技术社区  ›  Justin808

匹配img src=“*”类型URL的c#正则表达式

  •  1
  • Justin808  · 技术社区  · 15 年前

    问题是正则表达式将不匹配以下内容:

    <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);
        }
    }
    
    4 回复  |  直到 15 年前
        1
  •  3
  •   Community Mohan Dere    8 年前

    使用RegEx以这种方式解析图像是个坏主意。看到了吗 here 为了证明原因。

    您可以使用HTML解析器,例如 HTML Agility Pack 解析HTML并使用XPath语法进行查询。

        2
  •  1
  •   µBio    15 年前

    首先,我将尝试跳过所有的手动解析和使用 linq to html

    HDocument document = HDocument.Load("http://www.microsoft.com");
    
    foreach (HElement element in document.Descendants("img"))
    {
       Console.WriteLine("src = " + element.Attribute("src"));
    }
    

    如果这不起作用,只有到那时我才能回到手动解析,我相信这里的一个优秀的温和的人已经发布了一个工作正则表达式为您的需要。

        3
  •  0
  •   mkoryak    15 年前

    正则表达式是个坏主意。最好使用html解析器。下面是一个正则表达式,我用来解析正则表达式的链接:

    String body = "..."; //body of the page
    Matcher m = Pattern.compile("(?im)(?:(?:(?:href)|(?:src))[ ]*?=[ ]*?[\"'])(((?:http|https)(?::\\/{2}[\\w]+)(?:[\\/|\\.]?)(?:[^\\s\"]*))|((?:\\/{0,1}[\\w\\.]+)+))[\"']").matcher(body);
    while(m.find()){
      String absolute = m.group(2);
      String relative = m.group(3);
    }
    

    不过,使用解析器要容易得多,而且在资源方面也更好。下面是一个链接,显示了我在切换到解析器时最终编写的内容。

    http://notetodogself.blogspot.com/2007/11/extract-links-using-htmlparser.html

        4
  •  0
  •   Kendrick    15 年前