I'm trying to validate password which should not allow 3 repeating characters regardless of their position in the string.
For example :
121121 - Not Accepted, since 1 appears more than 3 times.
121212 - accepted, since 1 and 2 appears only 3 times
I tried this
([0-9])\1{2,}
But its validating only consecutive repeated digits.
A repeat is an expression that is repeated an arbitrary number of times. An expression followed by '*' can be repeated any number of times, including zero. An expression followed by '+' can be repeated any number of times, but at least once.
It means "Match zero or one of the group preceding this question mark." It can also be interpreted as the part preceding the question mark is optional. In above example '?' indicates that the two digits preceding it are optional. They may not occur or occur at the most once.
* - means "0 or more instances of the preceding regex token"
I don't recommend using regular expressions for something like this, as it would be easier to just collect the password into a Map
where a count of each character is maintained. Then, you can just check if there exists any character which has a count of more than 3
:
password.chars()
.boxed()
.collect(Collectors.groupingBy(i -> i, Collectors.counting()))
.values()
.stream()
.anyMatch(i -> i > 3);
This returns true
if there exists some character in password
that appears more than 3
times, and false
otherwise.
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