As we’ve repeatedly seen, parentheses are special characters in regular expressions, but in this case we want to allow a user to enter parentheses and have our regex recognize them.
⋯ # [Match the remaining digits and separator.] $ # Assert position at the end of the string..
Fortunately, Java Script 1.2 has incorporated regular expressions.
Since a question mark is used after each separator, the phone number digits are allowed to run together.
Note that although this recipe claims to handle North American phone numbers, it’s actually designed to work with (NANP) numbers.
Once you master the pattern language, most validation tasks become trivial.
You can perform complex tasks that once required lengthy procedures with just a few lines of code using regular expressions.
NET), get your very own copy of , so that your phone number records are consistent. The parentheses that appear without backslashes are capturing groups and are used to remember the values matched within them so that the matched text can be recalled later.
A regular expression can easily check whether a user entered something that looks like a valid phone number. In this case, backreferences to the captured values are used in the replacement text so we can easily reformat the phone number as needed.Patterns are defined using string literal characters and metacharacters.For example, the following regular expression determines whether a string contains a valid 5-digit US postal code (for sake or simplicity, other possibilities are not considered): Translated to English, this pattern states: "Starting at the beginning of the string there must be nothing other than 5 digits.This is important because there is no word boundary to be matched between two nonword characters, such as the opening parenthesis and a preceding space character.The first word boundary is relevant only when matching a number without parentheses, since the word boundary always matches between the opening parenthesis and the first digit of a phone number.The following layout breaks the regular expression into its individual parts, omitting the redundant groups of digits: ^ # Assert position at the beginning of the string. Any quantifier that allows something to be repeated zero times effectively makes that element optional.