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";
}
}
Maybe, an expression similar to,
(?:1[ -])?[(]?(\d{3})[)]?[ -](\d{3})[ -](\d{4})$
might cover the samples presented in the question, yet there'd probably be edge cases, such as any unexpected double space.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegularExpression{
public static void main(String[] args){
final String regex = "(?m)(?:1[ -])?[(]?(\d{3})[)]?[ -](\d{3})[ -](\d{4})$";
final String string = "(123)-456-7890\n"
+ "123-456-7890\n"
+ "1-(123)-456-7890\n"
+ "1-123-456-7890\n"
+ "(123) 456-7890\n"
+ "123 456-7890\n"
+ "1-(123) 456-7890\n"
+ "1-123 456-7890\n"
+ "(123) 456 7890\n"
+ "123 456 7890\n"
+ "1 123 456 7890\n"
+ "1 (123) 456 7890";
final String subst = "1-$1-$2-$3";
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
final String result = matcher.replaceAll(subst);
System.out.println(result);
}
}
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
1-123-456-7890
If you wish to simplify/update/explore the expression, it's been explained on the top right panel of regex101.com. You can watch the matching steps or modify them in this debugger link, if you'd be interested. The debugger demonstrates that how a RegEx engine might step by step consume some sample input strings and would perform the matching process.
jex.im visualizes regular expressions: