首页 > 解决方案 > RegEx,VB.Net:在 HTML 中查找链接(jepp,再次)

问题描述

首先,我的第一篇文章,所以如果我错过了什么,请原谅我。

问题很简单。我想从 html 文档中提取所有链接。当然,我正在寻找解决方案。我尝试了至少 30 个,但没有一个效果足够好,大多数根本不起作用。

我最终得到了这个(VB.Net):

    Dim rx As New System.Text.RegularExpressions.Regex("<a\s+(?:[^>]*?\s+)?href=""([^""]*)""")

    ' Get regex matches
    Dim mt As System.Text.RegularExpressions.MatchCollection = rx.Matches( _
      "sdfhjkl<a title=""datenkrake"" href=""http://www.google.de"">sdfghj</a>dfTHISISNOTALINK " & _
      "href=""narf.com""ghjkl<a href=""www.bing.de"" rel=""not really..."">bullshit</a>df<a href=""/"">local stuff</a>ghj" _
    )

    ' Check regex matches
    Diagnostics.Debug.WriteLine("Matches: " & mt.Count)
    For i As Integer = 0 To mt.Count - 1
        Diagnostics.Debug.WriteLine("  " & mt(i).Value)
    Next

    Diagnostics.Debug.WriteLine("----------")

    ' Get URLs from the results
    For i As Integer = 0 To mt.Count - 1
        Diagnostics.Debug.WriteLine("  " & mt(i).Value.Substring(mt(i).Value.TrimEnd("""").LastIndexOf("""")).Trim(""""))
    Next

调试输出:

    Matches: 3
      <a title="datenkrake" href="http://www.google.de"
      <a href="www.bing.de"
      <a href="/"
    ----------
      http://www.google.de
      www.bing.de
      /

这(下线)正是我想要的。但是如果没有所有这些 trim 和 lastindexof 的东西,这个输出不是可能的吗?

我很确定我永远不会理解这个笑脸 g@ngbang(又名正则表达式)......但对于这种情况,性能很重要。

提前致谢!

标签: regexvb.net

解决方案


推荐阅读