Shawn Mclean
Shawn Mclean

Reputation: 57479

Parse plain email address into 2 parts

How do I get the username and the domain from an email address of:

string email = "[email protected]";
//Should parse into:
string username = "hello";
string domain = "example.com";

I'm seeking the shortest code to do this, not necessarily efficient.


Scenario: I want to parse it in my ASP.NET MVC view so I can cloak it.

Upvotes: 45

Views: 36955

Answers (5)

Brian R. Bondy
Brian R. Bondy

Reputation: 347626

Use the MailAddress class

MailAddress addr = new MailAddress("[email protected]");
string username = addr.User;
string domain = addr.Host;

This method has the benefit of also parsing situations like this (and others you may not be expecting):

MailAddress addr = new MailAddress("\"Mr. Hello\" <[email protected]>");
string username = addr.User;
string host = addr.Host;

In both cases above:

Debug.Assert(username.Equals("hello"));
Debug.Assert(host.Equals("site.example"));

At the top of your file with the rest of your using directives add:

using System.Net.Mail;

Upvotes: 122

Tushar patel
Tushar patel

Reputation: 3407

Use this it will not give exception when no domain or username found instead it will give null value for that,

C# :

string email = "[email protected]";

string username = email.Split('@').ElementAtOrDefault(0);
string domain = email.Split('@').ElementAtOrDefault(1);

VB :

Dim email as String = "[email protected]";
Dim username = email.Split("@".ToCharArray()).ElementAtOrDefault(0);
Dim domain = email.Split("@".ToCharArray()).ElementAtOrDefault(1);

Upvotes: 2

Brad Christie
Brad Christie

Reputation: 101614

String[] parts = "[email protected]".Split(new[]{ '@' });
String username = parts[0]; // "hello"
String domain = parts[1]; // "example.com"

Upvotes: 15

Jonathan Wood
Jonathan Wood

Reputation: 67355

int i = email.IndexOf('@');
if (i >= 0)
{
    username = email.Substring(0, i);
    domain = email.Substring(i + 1);
}

Upvotes: 1

hunter
hunter

Reputation: 63562

string username = email.Split('@')[0];
string domain = email.Split('@')[1];

Upvotes: 8

Related Questions