Regular expressions CONTINUED

validate an email address

var re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
  1. ^ means anchor to the start of the string.
  2. \w identical to the pattern [a-zA-Z0-9_].
  3. + means one or more of the preceding.
  4. (, the left paren, means we're grouping everything to the matching ).
  5. [ ], the matching brackets indicate we match exactly one of the characters listed. I.e., '.' and '-' will match. The successful string will have one or the other in the indicated position. Since '.' has a special meaning (matches any single character except the newline '\n' character) it has to be escaped in order to specify the '.'.
  6. ? means zero or one of the previous item.
  7. \w as above.
  8. ) is the closing paren of the group.
  9. * means zero or more of the previous item.
  10. @ stands for @
  11. \w as above.
  12. ( as above (grouping).
  13. \. as above, matches '.'
  14. \w{2, 3} either two or three repetitions of the previous item.
    If we had \w{4, 10}, that would mean 4 or 5 or ... or 10 repetitions of [a-zA-Z0-9_]
  15. + means one or more repetitions of the previous item.
  16. $ means anchor to the end of the string.

Methods

A RegExp object has only a few, but extremely useful methods. A String object has a few (extremely useful) methods that can take a RegExp paramemter.

 RegExp.exec(string)
 RegExp.test(string)
 String.match(pattern)
 String.search(pattern)
 String.replace(pattern)
 String.split(pattern)
 

Test out some regular expression patterns