Dave Mackey
Dave Mackey

Reputation: 4432

Eliminate Portion of String in VB.NET

Lets say I have a variable: varEmail. It contains a variable equal to the user's email address, so it might contain a value like:

"[email protected]"

Now, lets say I want to get just a portion of the email address, e.g. strip off the domain, like so:

"myemail"

How can I accomplish this in VB.NET with string manipulation? I know this must be simple...maybe it is just early in the morning...

Upvotes: 0

Views: 152

Answers (5)

Matt
Matt

Reputation: 1911

If you know you are always dealing with valid email addresses, the easiest way might be as so:

varEmail = varEmail.Split("@"c)(0)

Upvotes: 4

Maxi
Maxi

Reputation: 79

You can use Split method. For example:

Dim MyString As String = "[email protected]"
Dim MyString2() As String
Dim MyString3 As String

MyString2 = Split(MyString, "@", -1, CompareMethod.Binary)
MyString3 = MyString2(0)

Now MyString3 = myemail

Upvotes: 1

Sankalp
Sankalp

Reputation: 939

Here is the solution for your problem:

Dim value, result as string

     value="[email protected]"
       result = value.Substring(0, value.IndexOf('@')+1)

I hope this will help you out.

Upvotes: 0

NoAlias
NoAlias

Reputation: 9193

For the fun of it, here is a more old school approach that still works in .Net (and like Matt's answer, this assumes you know this is a valid E-mail Address)...

strResult = Mid(varEmail, 1, (InStr(varEmail, "@") - 1))

If you aren't sure you have a valid e-mail do this in a try catch (it will throw an exception if the e-mail is not valid)...

Dim objMail As New System.Net.Mail.MailAddress(varEmail)
strResult = objMail.User

Upvotes: 2

UnhandledExcepSean
UnhandledExcepSean

Reputation: 12804

The first one gives the email name; the second gives the domain name.

dim varEmail as string="[email protected]"
MsgBox(varEmail.Substring(0, varEmail.IndexOf("@")))
MsgBox(varEmail.Substring(varEmail.IndexOf("@") + 1))

Upvotes: 4

Related Questions