-1

Possible Duplicate:
What is the best regular expression for validating email addresses?

I have a regular expression that validates email addresses:

/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/

It fails on these types though:

a.whatever@whatever.com

When the . before the @ is preceded by a single character the validation fails. I'm new to regular expressions, can someone help me allow those types of email addresses?

Community
  • 1
  • 1
user1087973
  • 800
  • 3
  • 12
  • 29

1 Answers1

2

Change the + quantifier to *:

/^[A-z_][A-z0-9_]*([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/
-----------------^

Note: I also changed [^0-9] to [A-z_], which makes more sense in terms of your rules.

  • Correct. The problem was with the '+' meaning that the original regex required at least two characters before the dot. – ArjunShankar Dec 20 '11 at 20:04
  • 1
    `[A-z]` matches the uppercase and lowercase ASCII letters, *plus* the six punctuation characters whose code points happen to lie between `Z` and `a`. So it's equivalent to ```[A-Z\[\\\]^_`a-z]```. I thought you were ready for the rice paper test, Tim, but I guess it's back to "wax on, wax off" for you. :D – Alan Moore Dec 20 '11 at 20:30
  • @AlanMoore: I was just copying the already defined character class OP was using. I've updated my answer to clarify your point. Thanks for the note! –  Dec 20 '11 at 20:41
  • So, do you believe the OP really wanted to match square brackets, backslashes, etc. in addition to letters? Using `[A-z]` as a shorthand for all letters is a common error among regex beginners, and by copying it without comment you're validating it. – Alan Moore Dec 20 '11 at 21:09