如何:在 Visual Basic 中识别 HTML 字符串中的超链接

本示例演示一个用于在 HTML 文档中标识超链接的简单正则表达式。

示例

本示例使用正则表达式 <A[^>]*?HREF\s*=\s*"([^"]+)"[^>]*?>([\s\S]*?)<\/A>,其含义为:

  1. 字符串“<A”,后接

  2. 零个或更多个字符的最小集合(不包含字符“>”),后接

  3. 字符串“HREF”,后接

  4. 零个或更多个空格字符,后接

  5. 字符“=”,后接

  6. 零个或更多个空格字符,后接

  7. 引号字符,后接

  8. 不包含引号字符(已捕获)的字符集合,后接

  9. 引号字符,后接

  10. 零个或更多个字符的最小集合(不包含字符“>”),后接

  11. 字符“>”,后接

  12. 零个或更多个已捕获的字符的最小集合,后接

  13. 字符串“</A>”。

Regex 对象用正则表达式进行初始化,并被指定为区分大小写。

Regex 对象的 Matches 方法返回一个 MatchCollection 对象,该对象包含有关正则表达式匹配的输入字符串的所有部分的信息。

    ''' <summary>Identifies hyperlinks in HTML text.</summary>
    ''' <param name="htmlText">HTML text to parse.</param>
    ''' <remarks>This method displays the label and destination for
    ''' each link in the input text.</remarks>
    Sub IdentifyLinks(ByVal htmlText As String)
        Dim hrefRegex As New Regex( 
            "<A[^>]*?HREF\s*=\s*""([^""]+)""[^>]*?>([\s\S]*?)<\/A>", 
            RegexOptions.IgnoreCase)
        Dim output As String = ""
        For Each m As Match In hrefRegex.Matches(htmlText)
            output &= "Link label: " & m.Groups(2).Value & vbCrLf
            output &= "Link destination: " & m.Groups(1).Value & vbCrLf
        Next
        MsgBox(output)
    End Sub

此示例要求您使用 Imports 语句来导入 System.Text.RegularExpressions 命名空间。 有关更多信息,请参见 Imports 语句(.NET 命名空间和类型)

请参见

概念

示例:扫描 HREF

其他资源

分析字符串 (Visual Basic)