Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to validate 3 repeating characters

Tags:

java

regex

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.

like image 871
Chris Avatar asked May 17 '18 15:05

Chris


People also ask

How do you repeat in regex?

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.

What is '?' In regex?

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.

Why * is used in regex?

* - means "0 or more instances of the preceding regex token"


1 Answers

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.

like image 57
Jacob G. Avatar answered Oct 23 '22 21:10

Jacob G.