简体   繁体   中英

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");
    }
}

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.

You can use back-reference like (\\\\d)\\\\1 . (eg (\\\\d)\\\\1\\\\d* ).

Where

  1. the first \\\\d means a digit
  2. \\\\1 means the same digit and
  3. \\\\d* means 0 or more digit(s).

If the length of the number is not a matter you can use this. Since you are using java you need two slashes.
String Golden = "(\\\\d)\\\\1\\\\d*";

If the length of the number should exactly be eight

String Golden = "(\\\\d)\\\\1\\\\d{6}";

If you want to match five repeated numbers,
String Golden = "(\\\\d)\\\\1{4}\\\\d*";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM