I have a method which receives a contact in one of the following formats:
1 - "email@domain.com"
2 - "Name <email@domain.com>" OR "Name<email@domain.com>" (Spaces can exist)
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.
How can I do this?
MailAddress
is a great solution, but unfortunatelySystem.Net.Mail
has not yet been ported to .NET Core.I find that the following Regex solution works for reasonably well-formed inputs:
I have tested this with the following kinds of inputs:
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.
First include
using System.Net.Mail
and then you can get the info with something like this:This will work with the two scenarios that you described so
"Name <email@domain.com>"
and"Name<email@domain.com>"
both work and give youName
. I went on and created a test that can be found here that will give you the sample output of:There's few ways to do that, but first one that occurred was
You may use Regex:
Here I assume that you needn't validate email format and name doesn't have < or > characters
You could use a regex.
The name (if available) would be in the second capturing group, and the email would be in the third.
Example:
You can either design a simple regular expression (which would, in my opinion, be the elegant solution in this case) or call
Split()
with'<'
as the separator,Trim()
the first string and remove the closing'>'
from the second one.