简体   繁体   English

正则表达式电话号码模式

[英]regex telephone number pattern

I have 3 categories of telephone number that is Golden, Special and Normal. 我有3类电话号码,分别是Golden,Special和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.). 让我举一个Golden类别编号的例子:AA001234(AA表示2位数,相同的数字如11,22,33等)。 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: 我不确定Java是否支持完整的正则表达式实现,但如果确实如此,您可以使用:

(\d)(\1)002345

\\1 means back reference to the first match (parenthesis-ed), so (\\d)(\\1) will match two same numbers consecutively. \\1表示对第一个匹配(括号编辑)的反向引用,因此(\\d)(\\1)将连续匹配两个相同的数字。

If Java does not support this, I suggest you to hard code it since you only have 3 categories. 如果Java不支持这个,我建议你硬编码,因为你只有3个类别。

You can use back-reference like (\\\\d)\\\\1 . 你可以像(\\\\d)\\\\1那样使用反向引用。 (eg (\\\\d)\\\\1\\\\d* ). (例如(\\\\d)\\\\1\\\\d* )。

Where 哪里

  1. the first \\\\d means a digit 第一个\\\\d表示一个数字
  2. \\\\1 means the same digit and \\\\1表示相同的数字和
  3. \\\\d* means 0 or more digit(s). \\\\d*表示0位或更多位。

If the length of the number is not a matter you can use this. 如果数字的长度不是一个问题,你可以使用它。 Since you are using java you need two slashes. 由于您使用的是Java,因此需要两个斜杠。
String Golden = "(\\\\d)\\\\1\\\\d*";

If the length of the number should exactly be eight 如果数字的长度恰好是8

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

If you want to match five repeated numbers, 如果你想匹配五个重复的数字,
String Golden = "(\\\\d)\\\\1{4}\\\\d*";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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