3

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

John Doe <john.doe@gmail.com>

If I use Regex.Match("John Doe <john.doe@gmail.com>", @"/([^<]+)\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.

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
Klaus Nji
  • 18,107
  • 29
  • 105
  • 185

3 Answers3

4

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

var match = Regex.Match("John Doe <john.doe@gmail.com>", @"([^<]+)\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 <john.doe@gmail.com>", @"(?<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>[^<>]*)>
Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
4

Alternative:

var m = new System.Net.Mail.MailAddress(@"John Doe <john.doe@gmail.com>");

Console.WriteLine(m.DisplayName);
Console.WriteLine(m.Address);
Alex K.
  • 171,639
  • 30
  • 264
  • 288
0

You can name your capturing groups:

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

Then you can use it like this:

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

var name = match.Groups["name"];
var email = match.Groups["email"];
Arturo Menchaca
  • 15,783
  • 1
  • 29
  • 53