Klaus Nji
Klaus Nji

Reputation: 18867

C# Regex to match name and email from header

I have this Regex @"/([^<]+)\s<(.*)>/" to match the name and email address from this string in C#:

John Doe <[email protected]>

If I use Regex.Match("John Doe <[email protected]>", @"/([^<]+)\s<(.*)>/") what is the property of the result that returns both the name and email address in a collection? I looked at Groups and Captures but neither returns the correct result.

Thanks.

Upvotes: 3

Views: 1025

Answers (3)

Alex K.
Alex K.

Reputation: 175916

Alternative:

var m = new System.Net.Mail.MailAddress(@"John Doe <[email protected]>");

Console.WriteLine(m.DisplayName);
Console.WriteLine(m.Address);

Upvotes: 4

Arturo Menchaca
Arturo Menchaca

Reputation: 15982

You can name your capturing groups:

(?<name>[^<]+)\s<(?<email>.*)>

Then you can use it like this:

var match = Regex.Match("John Doe <[email protected]>", @"(?<name>[^<]+)\s<(?<email>.*)>");

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

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627292

You need to remove the regex delimiters first. See this post explaining that issue.

var match = Regex.Match("John Doe <[email protected]>", @"([^<]+)\s<(.*)>");

Then, you can get the name and email via match.Groups[1].Value and match.Groups[2].Value respectively.

However, best is to use named capture groups:

var match = Regex.Match("John Doe <[email protected]>", @"(?<name>[^<]+)\s<(?<mail>.*)>");

Then, you can access these values with match.Groups["name"].Value and match.Groups["mail"].Value.

And one more note on the pattern: if the email does not contain > nor <, I'd advise to also use a negated character class [^<>] there (matching any character but < and >):

(?<name>[^<]+)\s<(?<mail>[^<>]*)>

Upvotes: 4

Related Questions