Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Parse String in format "Name <Email>"

Tags:

string

c#

parsing

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

1 - "[email protected]"

2 - "Name <[email protected]>" OR "Name<[email protected]>" (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?

like image 870
Miguel Moura Avatar asked Sep 15 '12 21:09

Miguel Moura


2 Answers

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:

MailAddress email = new MailAddress("Johnny <[email protected]>");
string displayName = email.DisplayName;
string address = email.Address;
string user = email.User;
string host = email.Host;

This will work with the two scenarios that you described so "Name <[email protected]>" and "Name<[email protected]>" 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 protected]' =
   DisplayName = ''
   Address = '[email protected]'
   User = 'email'
   Host = 'domain.com'
'Name<[email protected]>' =
   DisplayName = 'Name'
   Address = '[email protected]'
   User = 'email'
   Host = 'domain.com'
'Name <[email protected]>' =
   DisplayName = 'Name'
   Address = '[email protected]'
   User = 'email'
   Host = 'domain.com'
like image 134
Josh Bowden Avatar answered Oct 17 '22 14:10

Josh Bowden


MailAddress is a great solution, but unfortunately System.Net.Mail has not yet been ported to .NET Core.

I find that the following Regex solution works for reasonably well-formed inputs:

var re = new Regex(@"""?((?<name>.*?)""?\s*<)?(?<email>[^>]*)");
var match = re.match(input);

var name = match.Groups["name"].Value;
var email = match.Groups["email"].Value;

I have tested this with the following kinds of inputs:

[email protected]
<[email protected]>
Bob Example <[email protected]>
Bob Example<[email protected]>
"Bob Example" <[email protected]>
"Example, Bob J." <[email protected]>
like image 1
asherber Avatar answered Oct 17 '22 13:10

asherber