I might've got thins too complicated, so I'll publish my staff here. All the numbers I'm testing in the main method are marked as false. Is it the way I'm using regexes wrong, or my whole logic? I'd be grateful for some guidance:)
package com.codegym.task.task22.task2212;
/*
Phone number verification
*/
public class Solution {
public static boolean checkPhoneNumber(String phoneNumber) {
boolean isValid = false;
// null check, "" check, check for letters (crit 6)
if (phoneNumber == null || phoneNumber.isEmpty() || phoneNumber.matches(".*[a-zA-Z].*")) return isValid;
// check for ending with a digit (crit 7)
if (phoneNumber.matches("\\d$")) {
// case: start with a plus (crit 1)
if (phoneNumber.startsWith("+")) {
// check if there are 12 digits present (crit 1)
if (phoneNumber.matches("(?=.*\\d{12}.*)")) {
// check if no 2 dashes are consecutive (crit 2),
// ...if there are (optional) parentheses with 3 digits inside (crit 4, 5)
// ...to the left of the optional dashes, which can be from 0 to 2 (crit 2)
isValid = phoneNumber.matches("^(?!.*--)(\\(\\d{3}\\))?([\\d]*-?[\\d]*){0,2}$");
}
}
// check for a start with an opening parentheses or a digit (crit 2)
else if(phoneNumber.startsWith("(") || phoneNumber.matches("^\\d.*")) {
// check if there are 10 digits present (crit 2)
if (phoneNumber.matches("(?=.*\\d{10}).*"))
// check if no 2 dashes are consecutive (crit 2),
// ...if there are (optional) parentheses with 3 digits inside (crit 4, 5)
// ...to the left of the optional dashes, which can be from 0 to 2 (crit 2)
isValid = phoneNumber.matches("^(?!.*--)(\\(\\d{3}\\))?([\\d]*-?[\\d]*){0,2}$");
}
}
return isValid;
}
public static void main (String[]args){
System.out.println(checkPhoneNumber("+380501234567")); // - true
System.out.println(checkPhoneNumber("+38(050)1234567")); // - true
System.out.println(checkPhoneNumber("+38050123-45-67")); // - true
System.out.println(checkPhoneNumber("050123-4567")); // - true
System.out.println(checkPhoneNumber("+38)050(1234567")); // - false
System.out.println(checkPhoneNumber("+38(050)1-23-45-6-7")); // - false
System.out.println(checkPhoneNumber("050xxx4567")); // - false
System.out.println(checkPhoneNumber("050123456")); // - false
System.out.println(checkPhoneNumber("(0)501234567")); // - false
}
}
int digitsCount = "+1(001)1-2-3".replaceAll("\\D+", "").length();
). Then you continue with further checks.