Regular Expression for domain from email address

Wow, all the answers here are not quite right.

An email address can have as many "@" as you want, and the last one isn't necessarily the one before the domain :(

for example, this is a valid email address:

[email protected](i'm a comment (with an @))

You'd have to be pretty mean to make that your email address though.

So first, parse out any comments at the end.

Then

int atIndex = emailAddress.LastIndexOf("@");
String domainPart = emailAddress.Substring(atIndex + 1);

This is a general-purpose e-mail matcher:

[a-zA-Z][\w\.-]*[a-zA-Z0-9]@([a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z])

Note that it only captures the domain group; if you use the following, you can capture the part proceeding the @ also:

([a-zA-Z][\w\.-]*[a-zA-Z0-9])@([a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z])

I'm not sure if this meets RFC 2822, but I doubt it.


@(.*)$

This will match with the @, then capture everything up until the end of input ($)


A regular expression is quite heavy machinery for this purpose. Just split the string containing the email address at the @ character, and take the second half. (An email address is guaranteed to contain only one @ character.)