0

I'm trying to create a EMAIL regular expression. This is what I'm trying to achieve:

“_A-Za-z0-9-” , optional follow by “.[_A-Za-z0-9-]“, and end with a “@” symbol. The email’s domain name must start with “A-Za-z0-9″, follow by first level Tld (.com, .net) “.[A-Za-z0-9]” and optional follow by a second level Tld (.com.au, .com.my) “ .[A-Za-z]{2,}”, where second level Tld must start with a dot “.” and length must equal or more than 2 characters.

This is what I have so far:

([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})(\w?\.[A-Za-z]{2,})

not working for me. I would like it to validate these emails:

myname@compgg.com
ffdicot@foobar.com.au
i3dicot@foobar.co.uk

and NOT:

myname@foobar.foo.bar.com

any suggestions?

Shmarman
  • 13
  • 1
  • 7
  • 1
    Suggestion: Don't do it. See also http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address – tripleee Sep 24 '12 at 14:22

1 Answers1

0

Don't.

This is the regexp corresponding to RFC2822:

(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])

Better to implement it as separate functions, where each one checks a different requirement...

Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130
  • You mean to split on "@" and test each part by itself? what would be the best/correct way to do this? – Shmarman Sep 24 '12 at 14:37