Regular expression for validating international phone numbers
New area codes that fit the rules listed earlier are made available regularly, and even if a phone number is valid, that doesn’t necessarily mean it was issued or is in active use.Two simple changes allow the previous regular expression to match phone numbers within longer text: matches the position between a word character and either a nonword character or the beginning or end of the text.The NANP is the telephone numbering plan for the countries that share the country code “1”.This includes the United States and its territories, Canada, Bermuda, and 16 Caribbean nations.‘$’ is used to stop matching too much string into final result than required., composing a fairly comprehensive guide to validating and formatting North American and international phone numbers using regular expressions. Thus, the sequences that enclose the first group of digits match literal parenthesis characters. 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.
This is a textbook example of where we need a backslash to escape a special character so the regular expression treats it as literal input.
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.
By using capturing groups to remember each set of digits, the same regular expression can be used to replace the subject text with precisely the format you want. Two other types of tokens used in this regular expression are character classes and quantifiers.
See Recipes 3.5 and 3.15 for help implementing this regular expression with other programming languages. Character classes allow you to match any one out of a set of characters.