I am wondering if there is a way to normalize the phone number to the North American standard (1-222-333-4444) using regex pattern.
The string will take either "-", whitespace, "(", ")", and numbers only.
Thank you :)
Updated: All possible input are:
(123)-456-7890
123-456-7890
1-(123)-456-7890
1-123-456-7890
(123) 456-7890
123 456-7890
1-(123) 456-7890
1-123 456-7890
(123) 456 7890
123 456 7890
1 123 456 7890
1 (123) 456 7890
Code attempt:
public String convertPhone(String newPhone) {
String regex = "^([\\(]{1}[0-9]{3}[\\)]{1}[ |\\-]{0,1}|^[0-9]{3}[\\-| ])?[0-9]{3}(\\-| ){1}[0-9]{4}$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(newPhone);
if (matcher.matches()) {
newPhone = matcher.replaceFirst("1 \\($1\\) $2-$3");
return newPhone;
} else {
return "-1";
}
}