Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for domain from email address

Can anyone help me with a regular expression that will return the end part of an email address, after the @ symbol? I'm new to regex, but want to learn how to use it rather than writing inefficient .Net string functions!

E.g. for an input of "[email protected]" I need an output of "example.com".

Cheers! Tim

like image 336
TimS Avatar asked Sep 28 '09 15:09

TimS


People also ask

How do I find the regex for a domain name?

The domain name should be a-z or A-Z or 0-9 and hyphen (-). The domain name should be between 1 and 63 characters long. The domain name should not start or end with a hyphen(-) (e.g. -geeksforgeeks.org or geeksforgeeks.org-). The last TLD (Top level domain) must be at least two characters and a maximum of 6 characters.

Can you tell a regular expression that accepts email?

[a-zA-Z0-9+_. -] matches one character from the English alphabet (both cases), digits, “+”, “_”, “.” and, “-” before the @ symbol. + indicates the repetition of the above-mentioned set of characters one or more times. @ matches itself.

What is the regex for email?

To get a valid email id we use a regular expression /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.

What is the domain of email address?

An email domain is the part of an email address that comes after the @ symbol. For personal emails, it is most often gmail.com, outlook.com or yahoo.com. However, in a business context, companies are almost certain to have their own email domain.


2 Answers

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.

like image 76
Paul Lammertsma Avatar answered Oct 14 '22 15:10

Paul Lammertsma


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);
like image 30
Neil McGuigan Avatar answered Oct 14 '22 16:10

Neil McGuigan