Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to check for a repeating digit

Tags:

java

regex

I have a Java application where users must specify a PIN to log in. When creating the PIN, there are only 3 requirements:

  • Must be 6 digits:

    \\d{6}
    
  • Must not have 4 or more sequential numbers:

    \\d*(0123|1234|2345|3456|4567|5678|6789)\\d*
    
  • Must not have a digit repeating 3 or more times (such as 000957 or 623334 or 514888): This is where I'm stuck...

I have tried:

\\d*(\\d)\\1{3}\\d*

but I believe the \1 is looking at the initial match to the \d* not the second match of (\d).


Answer used: I have updated to using:
\\d{6}
(0123|1234|2345|3456|4567|5678|6789|9876|8765|7654|6543|5432|4321|3210)
\\d*?(\\d)\\1{2,}\\d*

To satisfy the initially stated requirements plus a few I hadn't thought of! Thanks for all the help

like image 576
D.R. Avatar asked Dec 06 '22 17:12

D.R.


2 Answers

Your regex is slightly off, since the first \d will match the first number. You only want to match 2 more after that.

\\d*(\\d)\\1{2}\\d*

should do the trick.

Quick edit: If you want to match 2 or more numbers in sequence, just add a comma to your count, without specifying a maximum number:

\\d*(\\d)\\1{2,}\\d*

Or at least, this works in Perl. Let us know how you go.

like image 120
Rohaq Avatar answered Dec 09 '22 05:12

Rohaq


Do you want to block three repeating following numbers or just more than three numbers in general (such as in "112213")?

If the latter one is the case, Regex might not be the best solution to a problem:

public static boolean validate(String pin){
    if (pin == null || pin.length() != 6)
        return false;

    int[] count = new int[10];
    for (int i = 0; i < pin.length(); i++) {
        char c = pin.charAt(i);
        if(!Character.isDigit(c))
            return false;

        if (++count[c - '0'] > 3)
            return false;
    }

    return true;
}
like image 25
Matthias Avatar answered Dec 09 '22 05:12

Matthias