Telehpone number validator reg expression is below
For a telephone number validator we need a regualar expression that does the following
Start with an ( so the carrot character ^ Then we should have a ( as a first character [(] . \ is used as an escape character for ( .Then {1} quantifier means there can be only 1 ( Then there will be 3 nos from 1-9 . so we use quantifier {3} The there should be only 1 closing parenthesis [)]{1}
Then there should be only one blank space [ ]{1}
And then 3 nos from 1 to 9 }[0-9]{3} Then one - .[-]{1} Another 4 nos from 1-9 [0-9]{4} And it should end after that. that is nothing after that so we close the bracket that we started right after the carrot character ^ in the very beginning and put dollar sign $
//^([\(]{1}[0-9]{3}[\)]{1}[ ]{1}[0-9]{3}[\-]{1}[0-9]{4})$
Code to test the above regular expression is below
String phoneNumber1 = "1234567890";
String phoneNumber2= "(123) 456-7890";
String phoneNumber3 = "123 456-7890";
String phoneNumber4 = "(123)456-7890";
System.out.println("phone1 "+ phoneNumber1.matches("^([\\(]{1}[0-9]{3}[\\)]{1}[ ]{1}[0-9]{3}[\\-]{1}[0-9]{4})$"));
System.out.println("phone2 "+ phoneNumber2.matches("^([\\(]{1}[0-9]{3}[\\)]{1}[ ]{1}[0-9]{3}[\\-]{1}[0-9]{4})$"));
System.out.println("phone3 "+ phoneNumber3.matches("^([\\(]{1}[0-9]{3}[\\)]{1}[ ]{1}[0-9]{3}[\\-]{1}[0-9]{4})$"));
System.out.println("phone4 "+ phoneNumber4.matches("^([\\(]{1}[0-9]{3}[\\)]{1}[ ]{1}[0-9]{3}[\\-]{1}[0-9]{4})$"));