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.
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.
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];
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.