Общий шаблон регулярных выражений, который может работать здесь:
^(?:\(\d{3}\)\s*|\d{3}-)\d{3}-\d{4}$
Вот объяснение приведенного выше регулярного выражения:
^ from the start of the input
(?:
\(\d{3}\) match (xxx)
\s* followed by optional whitespace
| OR
\d{3}- xxx-
)
\d{3}-\d{4} match xxx-xxxx
$ end of the input
Демо
Это будет охватывать обе версии номера телефона, который вы дали выше. В Java мы можем использовать String#matches
здесь:
String phone1 = "(555) 555-5555";
String phone2 = "555-555-5555";
if (phone1.matches("(?:\\(\\d{3}\\)\\s*|\\d{3}-)\\d{3}-\\d{4}")) {
System.out.println(phone1 + " is in a valid format");
}
if (phone2.matches("(?:\\(\\d{3}\\)\\s*|\\d{3}-)\\d{3}-\\d{4}")) {
System.out.println(phone2 + " is in a valid format");
}