Share via


How to: Parse E-mail Addresses in Visual BasicĀ 

This example demonstrates a simple regular expression for parsing an e-mail address.

Example

This example uses the regular expression (\S+)@([^\.\s]+)(?:\.([^\.\s]+))+, which means:

  1. Set of one or more non-space characters (captured), followed by

  2. The character "@", followed by

  3. Set of one or more non-space and non-period characters (captured), followed by

  4. One or more of the following:

    1. The character ".", followed by

    2. Set of one or more non-space and non-period characters (captured).

The regular expression's Match method returns a Match object that contains information about what part of the input string the regular expression matches.

    ''' <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

This example requires that you use the Imports statement to import the System.Text.RegularExpressions namespace. For more information, see Imports Statement.

See Also

Tasks

How to: Verify That Strings are in Valid E-Mail Format

Other Resources

Parsing Strings in Visual Basic