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*
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)
.
\\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
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With