0

I am really bad at regex and would to to parse an email address using c#.

If my input is user@domain.me.com, what regex would I use to extract just the "domain" part? There can be multiple domains that are of different length.

Justin R.
  • 23,435
  • 23
  • 108
  • 157
Raj
  • 549
  • 2
  • 11
  • 25
  • so, you want the text between the `@` and the following `.`? – Jonesopolis Nov 06 '14 at 00:14
  • 1
    you can do this several ways that do not require `RegEx` for example are you familiar with `IndexOf()` method or `Split()` method..? – MethodMan Nov 06 '14 at 00:15
  • yes, the text between @ and the following . – Raj Nov 06 '14 at 00:15
  • I haven't use either methods. But I will look into those also. – Raj Nov 06 '14 at 00:17
  • 1
    `Raj` here are some other good examples to look at as well.. http://stackoverflow.com/questions/16473838/get-domain-name-of-a-url-in-c-sharp-net also `GOOGLE.COM` is your best friend use it.. – MethodMan Nov 06 '14 at 00:20

2 Answers2

4

It's not trivial to parse an email with a regex, because the rules for a valid email are complex; fortunately, you don't need to: you can use the MailAddress class instead.

var address = new MailAddress("user@domain.me.com");
string domain = address.Host.Split('.')[0];
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
1

Use a positive look-behind to find the @, then grab text till a .:

(?<=@)[^\.]+

in code you could use:

var str = "user@domain.me.com";
var domain = Regex.Match(str, @"(?<=@)[^\.]+").Groups[0].ToString();

you'll want to check your matches to ensure a match was found, I assume.

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112