views:

748

answers:

4

Hi,

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

+4  A: 

@(.*)$

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

Xetius
Thanks! I'm getting "@example.com". Can I get the value without the @?
TimS
You're probably not getting the right group. The parenthesis `(`, `)` indicate a group match, so make sure you grab the result from group with index 1, not 0 (as index #0 is always reserved for the entire expression match).
Paul Lammertsma
+1  A: 

A simple regex for your input is:

^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$

But, it can be useless when you apply for a broad and heterogeneous domains.

An example is:

^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)$

But, you can optimize that suffix domains as you need.

But for your suffix needs, you need just:

@.+$

Resources: http://www.regular-expressions.info/email.html

apast
actually the [regex is a bit longer](http://cpansearch.perl.org/src/RJBS/Email-Valid-0.182/lib/Email/Valid.pm)
xxxxxxx
I recommend this one over my solution as it is less restrictive.
Paul Lammertsma
Just don't forget to capture the domain into a group, as asked: `^[A-Z0-9._%+-]+@([A-Z0-9.-]+\.[A-Z]{2,4})$`
Paul Lammertsma
And, uh, don't forget to escape those '.'s, even in characters classes.
Marc Bollinger
+4  A: 

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.)

Stephan202
A: 

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.

Paul Lammertsma