When searching for RegExp patterns to validate an email address in Javascript, I found a pattern that Facebook uses from here.
function is_email(a){return /^([\w!.%+\-])+@([\w\-])+(?:\.[\w\-]+)+$/.test(a);}
Can someone please explain to me how this pattern works? I understand that it is looking for 'word characters' in three positions along with a '@' character. But a nice explanation will help a lot for me to understand this.
There are two websites (that I know of), which generate explanations for regex patterns.
Here is my own explanation for the pattern:
^ # anchor the pattern to the beginning of the string; this ensures that
# there are no undesired characters before the email address, as regex
# matches might well be substrings otherwise
( # starts a group (which is unnecessary and incurs overhead)
[\w!.%+\-]
# matches a letter, digit, underscore or one of the explicitly mentioned
# characters (note that the backslash is used to escape the hyphen
# although that is not required if the hyphen is the last character)
)+ # end group; repeat one or more times
@ # match a literal @
( # starts another group (again unnecessary and incurs overhead)
[\w\-] # match a letter, digit, underscore or hyphen
)+ # end group; repeat one or more times
(?: # starts a non-capturing group (this one is necessary and, because
# capturing is suppressed, this one does not incur any overhead)
\. # match a literal period
[\w\-] # match a letter, digit, underscore or hyphen
+ # one or more of those
)+ # end group; repeat one or more times
$ # anchor the pattern to the end of the string; analogously to ^
So, this would be a slightly optimised version:
/^[\w!.%+\-]+@[\w\-]+(?:\.[\w\-]+)+$/