In this regex tutorial, we will learn to validate user entered phone numbers for a specific format (in this example numbers are formatted in north American format) and if 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.
Using Regex to Validate North American Phone Numbers
Regex : ^\\(?([0-9]{3})\\)?[-.\\s]?([0-9]{3})[-.\\s]?([0-9]{4})$
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()); } 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
Using Regex to format North American Phone Numbers
Regex : ($1) $2-$3
Use above regex to reformat phone numbers validated in above step to reformat in a consistent way to store/display purpose.
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")); } } Output: (123) 456-7890 (123) 456-7890 (123) 456-7890 (123) 456-7890 (123) 456-7890
Above regex will work in java-script as well. So keep these regex handy when you need them next time.
Happy Learning !!
How do you ensure that all the valid phone numbers start with the digits “123”
Hi great website,
Do you know how to make a spellchecker with Soundex algorithm?
Thanks