In this regex tutorial, we will learn to validate user-entered phone numbers for a specific format (in this example phone numbers are formatted in North American format) and if the numbers are correct then reformat them to a standard format for display. I have tested formats including 1234567890, 123-456-7890, 123.456.7890, 123 456 7890, (123) 456 7890, and all such combinations.
1. Using Regex to Validate North American Phone NumbersRegex : ^\\(?([0-9]{3})\\)?[-.\\s]?([0-9]{3})[-.\\s]?([0-9]{4})$
The above regular expression can be used to validate all formats of phone numbers to check if they are valid North American phone numbers.
List phoneNumbers = new ArrayList();
phoneNumbers.add("1234567890");
phoneNumbers.add("123-456-7890");
phoneNumbers.add("123.456.7890");
phoneNumbers.add("123 456 7890");
phoneNumbers.add("(123) 456 7890");
//Invalid phone numbers
phoneNumbers.add("12345678");
phoneNumbers.add("12-12-111");
String regex = "^\\(?([0-9]{3})\\)?[-.\\s]?([0-9]{3})[-.\\s]?([0-9]{4})$";
Pattern pattern = Pattern.compile(regex);
for(String email : phoneNumbers)
{
Matcher matcher = pattern.matcher(email);
System.out.println(email +" : "+ matcher.matches());
}
The program output:
1234567890 : true
123-456-7890 : true
123.456.7890 : true
123 456 7890 : true
(123) 456 7890 : true
12345678 : false
12-12-111 : false
2. Using Regex to Format a North American Phone Number
Regex : ($1) $2-$3
Use the above regex to reformat phone numbers validated in the above step to reformat in a consistent way to store/display purposes.
List phoneNumbers = new ArrayList();
phoneNumbers.add("1234567890");
phoneNumbers.add("123-456-7890");
phoneNumbers.add("123.456.7890");
phoneNumbers.add("123 456 7890");
phoneNumbers.add("(123) 456 7890");
//Invalid phone numbers
phoneNumbers.add("12345678");
phoneNumbers.add("12-12-111");
String regex = "^\\(?([0-9]{3})\\)?[-.\\s]?([0-9]{3})[-.\\s]?([0-9]{4})$";
Pattern pattern = Pattern.compile(regex);
for(String email : phoneNumbers)
{
Matcher matcher = pattern.matcher(email);
//System.out.println(email +" : "+ matcher.matches());
//If phone number is correct then format it to (123)-456-7890
if(matcher.matches())
{
System.out.println(matcher.replaceFirst("($1) $2-$3"));
}
}
The program output:
(123) 456-7890
(123) 456-7890
(123) 456-7890
(123) 456-7890
(123) 456-7890
The above regex will work in JavaScript as well. So keep these regex handy when you need them next time.
Happy Learning !!
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4