Phone Number regex phone number

I have 3 categories of phone numbers that are gold, special and normal. What I'm trying to do is when a user enters a phone number, he will automatically determine which phone number belongs to which category. Let me give you an example of a golden category number: AA001234 (AA represents 2 digits with the same number as 11,22,33, etc.). Here is 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"); } } 
+4
source share
3 answers

I'm not sure that Java supports the full implementation of regular expressions, but if so, you can use:

 (\d)(\1)002345 

\1 means a backward reference to the first match (brackets-ed), so (\d)(\1) will match two identical numbers in series.

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

+2
source

You can use a backlink, for example (\\d)\\1 . (e.g. (\\d)\\1\\d* ).

Where

  • first \\d means digit
  • \\1 means the same digit and
  • \\d* means 0 or more digits.
+1
source

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

If the number must be exactly eight

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

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

+1
source

Source: https://habr.com/ru/post/1444504/


All Articles