regexvb.netstring-function

How to get string before a particular symbol within a string


Is there any way in vb.net to get the username from an email address?

For example, I've a string variable and it consists of value tracywilly@gmail.com, here I need to get the username i.e tracywilly is my expected output

Dim email_addr as string
Dim usr as string
email_addr = "tracywilly@gmail.com"

Solution

  • You can achieve this using split() or regex in vb.net

    see the following methods

    1.) split() function:

     Function username(ByVal str As String) As String
            Dim arStr As String()
            arStr = str.Split("@")
            username = arStr(0)
            Return username
        End Function
    

    2.) regex:

    Function username_1(ByVal str As String) As String
        username_1 = System.Text.RegularExpressions.Regex.Match(str, "^.*?(?=@)").ToString
        Return username_1
    End Function
    

    How does it work?

    Dim email_addr as string
    Dim usr as string
    email_addr = "tracywilly@gmail.com"
    usr = username(email_addr)
    usr = username_1(email_addr)
    

    Live Demo