Search code examples
javaregexphone-number

regex telephone number pattern


I have 3 categories of telephone number that is Golden, Special and Normal. What I'm trying to do is when the user key in the telephone number, It will automatically determine the telephone number belongs to which category. Let me give one example of Golden category number : AA001234 (AA represents 2 digits with the same number like 11,22,33 etc.). Here what I got

public static void main(String[] args) {

    Scanner userinput = new Scanner(System.in);

    System.out.println("Enter Telephone Number");
    String nophone = userinput.next();

    String Golden = "(\\d{2})002345"; // <-- how to write the code if the user
    //enter the same digit for the first 2 number, it will belong to Golden category?
    String Special1 = "12345678|23456789|98765432|87654321|76543210";

    if (nophone.matches(Golden)) {
        System.out.println("Golden");
    }

    else if (nophone.matches(Special1)) {
        System.out.println("Special 1");
    }
    else {
        System.out.println("Normal");
    }
}

Solution

  • I am not sure Java support full regex implementation, but if it does, you can use:

    (\d)(\1)002345
    

    \1 means back reference to the first match (parenthesis-ed), so (\d)(\1) will match two same numbers consecutively.

    If Java does not support this, I suggest you to hard code it since you only have 3 categories.