如何:在 Visual Basic 中分析电子邮件地址

此示例演示一个用于分析电子邮件地址的简单的正则表达式。

示例

本示例使用正则表达式 (\S+)@([^\.\s]+)(?:\.([^\.\s]+))+,其含义为:

  1. 一个或多个非空格字符集(已捕获),后跟

  2. 字符“@”,后跟

  3. 一个或多个非空格和非句点字符集(已捕获),后跟

  4. 一个或多个以下各项:

    1. 字符“.”,后跟

    2. 一个或多个非空格和非句点字符集(已捕获)。

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

    ''' <summary>
    ''' Parses an e-mail address into its parts.
    ''' </summary>
    ''' <param name="emailString">E-mail address to parse.</param>
    ''' <remarks> For example, this method displays the following 
    ''' text when called with "someone@mail.contoso.com":
    ''' User name: someone
    ''' Address part: mail
    ''' Address part: contoso
    ''' Address part: com
    ''' </remarks>
    Sub ParseEmailAddress(ByVal emailString As String)
        Dim emailRegEx As New Regex("(\S+)@([^\.\s]+)(?:\.([^\.\s]+))+")
        Dim m As Match = emailRegEx.Match(emailString)
        If m.Success Then
            Dim output As String = ""
            output &= "User name: " & m.Groups(1).Value & vbCrLf
            For i As Integer = 2 To m.Groups.Count - 1
                Dim g As Group = m.Groups(i)
                For Each c As Capture In g.Captures
                    output &= "Address part: " & c.Value & vbCrLf
                Next
            Next
            MsgBox(output)
        Else
            MsgBox("The e-mail address cannot be parsed.")
        End If
    End Sub

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

请参见

任务

如何:验证字符串是否为有效的电子邮件格式

其他资源

分析字符串 (Visual Basic)