1

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.

Community
  • 1
  • 1
user
  • 101
  • 1
  • 13
  • 2
    Here are two websites, that generate more-or-less useful explanations of regex patterns: http://www.regexper.com/ and http://regex101.com/ – Martin Ender May 01 '13 at 13:10
  • 1
    Thanks! That works. If you want to write that up as an answer, I'd be happy to accept it. – user May 01 '13 at 13:52

1 Answers1

0

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\-]+)+$/
Martin Ender
  • 43,427
  • 11
  • 90
  • 130