C# 从电子邮件地址获取域名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18980202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:46:56  来源:igfitidea点击:

Get domain name from an email address

c#emaildomain-name

提问by

I have an email address

我有一个电子邮件地址

[email protected]

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

我想从电子邮件地址获取域名。我可以用 Regex 实现这一点吗?

回答by Default

Using MailAddressyou can fetch the Hostfrom a property instead

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

MailAddress address = new MailAddress("[email protected]");
string host = address.Host; // host contains yahoo.com

回答by poke

Or for string based solutions:

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

string address = "[email protected]";
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);

回答by Chris

If Default's answeris not what you're attempting you could always Splitthe email string after the '@'

如果Default 的答案不是您要尝试的答案,您总是可以Split'@'

string s = "[email protected]";
string[] words = s.Split('@');

string[0]would be xyzif you needed it in future
string[1]would be yahoo.com

string[0]xyz,如果你需要它在未来
string[1]将是yahoo.com

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

但是 Default 的回答肯定是解决这个问题的更简单的方法。