58

I have an email address

xyz@yahoo.com

I want to get the domain name from the email address. Can I achieve this with Regex?

default
  • 11,485
  • 9
  • 66
  • 102

4 Answers4

136

Using MailAddress you can fetch the Host from a property instead

MailAddress address = new MailAddress("xyz@yahoo.com");
string host = address.Host; // host contains yahoo.com
default
  • 11,485
  • 9
  • 66
  • 102
29

If Default's answer is not what you're attempting you could always Split the email string after the '@'

string s = "xyz@yahoo.com";
string[] words = s.Split('@');

words[0] would be xyz if you needed it in future
words[1] would be yahoo.com

But Default's answer is certainly an easier way of approaching this.

harmstyler
  • 1,381
  • 11
  • 20
Chris
  • 915
  • 8
  • 28
  • 4
    Just as a heads up, email addresses can contain multiple "@". I'm pretty sure the last one will always separate the "user" from the "domain" though. – Chris Owens Apr 18 '19 at 04:36
10

Or for string based solutions:

string address = "xyz@yahoo.com";
string host;

// using Split
host = address.Split('@')[1];

// using Split with maximum number of substrings (more explicit)
host = address.Split(new char[] { '@' }, 2)[1];

// using Substring/IndexOf
host = address.Substring(address.IndexOf('@') + 1);
poke
  • 369,085
  • 72
  • 557
  • 602
0

Simple Substring Method will do the trick here

string emailAddress = @"myemail@gmail.com"; string domainName = emailAddress.Substring(emailAddress.IndexOf('.',emailAddress.LastIndexOf('@')));

Console.WriteLine (domainName);

Or If you have have bit of money you can get this library and that will do the work for you

https://afterlogic.com/mailbee-net/docs/MailBee.Mime.EmailAddress.GetDomain.html

  • 1
    I would add that, while MailBee.NET Objects is indeed a commercial product, some namespaces like MIME or HTML can be used at no cost. – Igor - AfterLogic Feb 16 '23 at 10:46