2

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
  • 85,718
  • 5
  • 90
  • 121
Klaus Nji
  • 16,937
  • 27
  • 100
  • 180

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
  • 561,645
  • 34
  • 376
  • 476
3

Alternative:

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

Console.WriteLine(m.DisplayName);
Console.WriteLine(m.Address);
Alex K.
  • 165,803
  • 30
  • 257
  • 277
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,395
  • 1
  • 28
  • 50