HOW TO:在 Visual Basic 中剖析電子郵件地址
更新:2007 年 11 月
以下為簡單規則運算式 (Regular Expression) 的範例,可用於剖析電子郵件地址。
範例
這個範例會使用規則運算式 (\S+)@([^\.\s]+)(?:\.([^\.\s]+))+,這表示:
一或多個非空白的字元集 (已擷取),後面緊接著
字元 "@",後面緊接著
一或多個非空白和非句號的字元集 (已擷取),後面緊接著
下列的一或多項:
字元 ".",後面緊接著
一或多個非空白和非句號的字元集 (已擷取)。
規則運算式的 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 命名空間和型別)。