简体   繁体   中英

Get domain name from an email address

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?

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

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM