4.2. Validate and Format North American Phone Numbers
Problem
You want to determine whether a user entered a North American
phone number in a common format, including the local area code.
These formats include 1234567890, 123-456-7890, 123.456.7890,
123 456
7890, (123)
456 7890, and all related combinations. If the phone
number is valid, you want to convert it to your standard format,
(123) 456-7890, so that your phone number
records are consistent.
Solution
A regular expression can easily check whether a user entered something that looks like a valid phone number. 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.
Regular expression
^\(?([0-9]{3})\)?[-.●]?([0-9]{3})[-.●]?([0-9]{4})$| Regex options: None |
| Regex flavors: .NET, Java, JavaScript, PCRE, Perl, Python, Ruby |
Replacement
($1)●$2-$3| Replacement text flavors: .NET, Java, JavaScript, Perl, PHP |
(\1)●\2-\3| Replacement text flavors: Python, Ruby |
C#
Regex regexObj =
new Regex(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$");
if (regexObj.IsMatch(subjectString)) {
string formattedPhoneNumber =
regexObj.Replace(subjectString, "($1) $2-$3");
} else {
// Invalid phone number
}JavaScript
var regexObj = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if (regexObj.test(subjectString)) {
var formattedPhoneNumber =
subjectString.replace(regexObj, "($1) $2-$3");
} else {
// Invalid phone number
}Other programming languages
See Recipes ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access