从电子邮件地址获取域名

时间:2013-09-24 11:19:50

标签: c# email domain-name

我有一个电子邮件地址

xyz@yahoo.com

我想从电子邮件地址获取域名。我能用Regex实现这个目标吗?

3 个答案:

答案 0 :(得分:74)

使用MailAddress,您可以从属性中获取Host

MailAddress address = new MailAddress("xyz@yahoo.com");
string host = address.Host; // host contains yahoo.com

答案 1 :(得分:21)

如果您Default's answer不是您正在尝试的内容,则Split

之后的电子邮件字符串始终为'@'
string s = "xyz@yahoo.com";
string[] words = s.Split('@');
如果您将来需要,

string[0]将为xyz string[1]将是yahoo.com

但默认的答案当然是一种更容易接近的方法。

答案 2 :(得分:6)

或者基于字符串的解决方案:

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