我需要从电子邮件地址字符串中获取主机。
在.net 4.x我这样做了
var email1 = "test@test.com";
var email2 = "test2@yea.test.com"
var email1Host = new MailAddress(email1).Host;
var email2Host = new MailAddress(email2).Host;
email1Host打印“test.com”
email2Host打印“yea.test.com”
但现在我只需要两个例子中的“test.com”部分。
.Net标准库1.6没有System.Net.Mail类,所以我不能再这样做了。
在.net核心中完成同样事情的另一种方式是什么,但我只需要test.com部分
我知道有一个System.Net.Mail-netcore nuget包,但我真的想避免为此安装一个nuget
编辑:对不起,我忘了提到我只需要test.com
要求提供更多示例
@ subdomain1.domain.co.uk => domain.co.uk
@ subdomain1.subdomain2.domain.co.uk => domain.co.uk
@ subdomain1.subdomain2.domain.com => domain.com
@ domain.co.uk => domain.co.uk
@ domain.com => domain.com
答案 0 :(得分:2)
使用String Split和Regex,
var email1 = "test@test.com";
var email2 = "test2@yea.test.co.uk";
var email1Host = email1.Split('@')[1];
var email2Host = email2.Split('@')[1];
Regex regex = new Regex(@"[^.]*\.[^.]{2,3}(?:\.[^.]{2,3})?$");
Match match = regex.Match(email1Host);
if (match.Success)
{
Console.WriteLine("Email Host1: "+match.Value);
}
match = regex.Match(email2Host);
if (match.Success)
{
Console.WriteLine("Email Host2: "+match.Value);
}
更新:使用正则表达式获取域名
答案 1 :(得分:1)
另一种方法是使用System.Uri
类,并在电子邮件前加上“mailto”。
class Program
{
static void Main(string[] args)
{
string email = "test@test.com";
string emailTwo = "test2@subdomain.host.com";
Uri uri = new Uri($"mailto:{email}");
Uri uriTwo = new Uri($"mailto:{emailTwo}");
string emailOneHost = uri.Host;
string emailTwoHost = uriTwo.Host;
Console.WriteLine(emailOneHost); // test.com
Console.WriteLine(emailTwoHost); // subdomain.host.com
Console.ReadKey();
}
}
答案 2 :(得分:0)
好吧,有点C#应该可以解决这个问题:
string email = "test@test.com";
int indexOfAt = email.IndexOf('@');
//You do need to check the index is within the string
if (indexOfAt >= 0 && indexOfAt < email.Length - 1)
{
string host = email.Substring(indexOfAt + 1);
}