[英]Parse plain email address into 2 parts
How do I get the username and the domain from an email address of:如何从以下电子邮件地址获取用户名和域:
string email = "hello@example.com";
//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.场景:我想在我的 ASP.NET MVC 视图中解析它,以便隐藏它。
Use the MailAddress class使用MailAddress类
MailAddress addr = new MailAddress("hello@site.example");
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\" <hello@site.example>");
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 指令一起添加:
using System.Net.Mail;
String[] parts = "hello@example.com".Split(new[]{ '@' });
String username = parts[0]; // "hello"
String domain = parts[1]; // "example.com"
string username = email.Split('@')[0];
string domain = email.Split('@')[1];
Use this it will not give exception when no domain or username found instead it will give null value for that,使用这个它不会在没有找到域或用户名时给出异常,而是会给出空值,
C# : C# :
string email = "hello@example.com";
string username = email.Split('@').ElementAtOrDefault(0);
string domain = email.Split('@').ElementAtOrDefault(1);
VB : VB:
Dim email as String = "hello@example.com";
Dim username = email.Split("@".ToCharArray()).ElementAtOrDefault(0);
Dim domain = email.Split("@".ToCharArray()).ElementAtOrDefault(1);
int i = email.IndexOf('@');
if (i >= 0)
{
username = email.Substring(0, i);
domain = email.Substring(i + 1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.