如何解析格式为“名称<电子邮件>"的字符串 [英] How To Parse String in format "Name <Email>"

查看:109
本文介绍了如何解析格式为“名称<电子邮件>"的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种方法可以接收以下格式之一的联系人:

I have a method which receives a contact in one of the following formats:

1-"email@domain.com"

1 - "email@domain.com"

2-名称"或名称"(可以存在空格)

2 - "Name <email@domain.com>" OR "Name<email@domain.com>" (Spaces can exist)

如果格式为(1),我什么也不做.对于(2),我需要解析名称和电子邮件.

If it is in format (1) I do nothing. In case of (2) I need to parse the name and email.

我不知道我将以哪种格式接收电子邮件.但这将是两者之一.

I never know in which format I will get the emails. But it will be one of the two.

我该怎么做?

推荐答案

实际上已经有一个名为

There is actually already a .NET class called MailAddress that can do this for you quite simply.
UPDATE: It can not only get the display name but also the email address, username, and host.

首先包含using System.Net.Mail,然后您可以通过以下方式获取信息:

First include using System.Net.Mail and then you can get the info with something like this:

MailAddress email = new MailAddress("Johnny <johnny@example.com>");
string displayName = email.DisplayName;
string address = email.Address;
string user = email.User;
string host = email.Host;

这将与您描述的两种情况一起使用,因此"Name <email@domain.com>""Name<email@domain.com>"都可以工作,并为您提供Name.我继续并创建了一个可以在此处找到的测试,它将为您提供以下示例输出:

This will work with the two scenarios that you described so "Name <email@domain.com>" and "Name<email@domain.com>" both work and give you Name. I went on and created a test that can be found here that will give you the sample output of:

'email@domain.com' =
   DisplayName = ''
   Address = 'email@domain.com'
   User = 'email'
   Host = 'domain.com'
'Name<email@domain.com>' =
   DisplayName = 'Name'
   Address = 'email@domain.com'
   User = 'email'
   Host = 'domain.com'
'Name <email@domain.com>' =
   DisplayName = 'Name'
   Address = 'email@domain.com'
   User = 'email'
   Host = 'domain.com'

这篇关于如何解析格式为“名称&lt;电子邮件&gt;"的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆