tags:

views:

43

answers:

5

Hi,

I was using a regular expression for email formats which I thought was ok but the customer is complaining that the expression is too strict. So they have come back with the following requirement:

The email must contain an "@" symbol and end with either .xx or .xxx ie.(.nl or .com). They are happy with this to pass validation. I have started the expression to see if the string contains an "@" symbol as below

^(?=.*[@])

this seems to work but how do I add the last requirement (must end with .xx or .xxx)?

+1  A: 

Try this :

([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})\be(\w*)s\b

A good tool to test our regular expression : http://gskinner.com/RegExr/

camilleb
Good answer, mainly, and the RegExp tester at gskinner is what I use too. I'm curious why you include literal "e" + any whitespace + "s" at the end. Your expression will fail at [email protected], for example. Simply using ([\w-\.]+)@((?:[\w]+\.)+)([a-zA-Z]{2,4})\b will succeed.
Robusto
A: 

You could use

[@].+\.[a-z0-9]{2,3}$
Dominik
Are digits allowed in top-level domains?
tur1ng
IPs are technically allowed in emails ... that's why I added the 0-9.
Dominik
+1  A: 

A regex simply enforcing your two requirements is:

^.+@.+\.[a-zA-Z]{2,3}$

However, there are email validation libraries for most languages that will generally work better than a regex.

Max Shawabkeh
+1  A: 

I always use this for emails

          ^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
            @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
            @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$

Try http://www.ultrapico.com/Expresso.htm as well!

Aim Kai
+1  A: 

It is not possible to validate every E-Mail Adress with RegEx but for your requirements this simple regex works. It is neither complete nor does it in any way check for errors but it exactly meets the specs:

[^@]+@.+\.\w{2,3}$

Explanation:

  • [^@]+: Match one or more characters that are not @
  • @: Match the @
  • .+: Match one or more of any character
  • \.: Match a .
  • \w{2,3}: Match 2 or 3 word-characters (a-zA-Z)
  • $: End of string
dbemerlin