Can someone explain this regular expression to validate email.
var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
I need to know what does this independent elements do
"/^" and "\" and "\.\-" and "$" //Please explain individually
Thanks in advance
-
regular-expressions.info/reference.htmlKJYe.Name– KJYe.Name2011年02月10日 13:47:45 +00:00Commented Feb 10, 2011 at 13:47
-
3That expression is broken and will reject many perfectly valid email addresses.Quentin– Quentin2011年02月10日 13:48:24 +00:00Commented Feb 10, 2011 at 13:48
-
possible duplicate of What is the best regular expression for validating email addresses?Brad Mace– Brad Mace2011年07月09日 04:32:25 +00:00Commented Jul 9, 2011 at 4:32
3 Answers 3
Quick explanation
/
JavaScript regular expressions start with a / and end with another one. Everything in-between is a regular expression. After the second / there may be switches like g (global) and/or i (ignore case) ie. var rx = /.+/gi;)
^
Start of a text line (so nothing can be prepended before the email address). This also comes in handy in multi-line texts.
\
Used to escape special characters. A dot/full-stop . is a special character and represents any single character but when presented as \. it means a dot/full-stop itself. Characters that need to escaped are usually used in regular expression syntax. (braces, curly braces, square brackets etc.) You'll know when you learn the syntax.
\.\-
Two escaped characters. Dot/full-stop and a minus/hyphen. So it means .-
$
End of line.
Learn regular expressions
They are one of the imperative things every developer should understand to some extent. At least some basic knowledge is mandatory.
Some resources
- General regular expression syntax resource
http://www.regular-expressions.info/ - JavaScript related regular expressions
https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Regular_Expressions
7 Comments
/^[0-9]+-?[0-9]+$/. And it also doesn't mean that it will be right in the middle. At least one digit will be proceeding it and at least one succeeding. But there may not be equal number of digits on each side./^[0-9]+\-[0-9]{1,2}+$/[0-9]. But even there it can be used freely when it can't make a conflict as in [0-9a-z.+-] All of these in a set are meant as literals.+ at the end. As long as you want these characters to be digits and not any characters. /^[0-9]+-?[0-9]{1,2}$/. AND if you do talk about digits, these two are equal: [0-9] = \d. So it can be shortened to: /^\d+-?\d{1,2}$/
/
The start of the expression
^
The start of the string (since it appears at the start of the expression)
\
Nothing outside the context of the character that follows it
\.\-
A full stop. A hyphen.
$
The end of the string
Comments
The other posters have done an excellent job at explaining this regex, but if your goal is to actually do e-mail validation in JavaScript, please check out this StackOverflow thread.