How to forbid a digit repeating n times with a regular expression

Here is my @Pattern annotation. I want to prohibit numbers repeating 9 times. What I did wrong?

@Pattern(regexp="(?!.*\\d{9})") 

These will be invalid strings:

 111111111 222222222 

They would be valid:

 111111112 222222221 123456789 

Only strings of length 9 will be valid, but this is not necessary as part of the regular expression, as this will be controlled by other annotations.

+4
source share
1 answer

Edited after comments

I think you mean that you do not want the same number to be repeated 9 times. To do this, you need to write down one digit and turn to it and see if it repeats another 8 times.

 @Pattern(regexp="^(?!(\\d)\\1{8})") 

If you just use \\d{9} , this will mean repeating any digits.

Also note that you do not need to .* . Regex will decide where to start the match on its own.

+4
source

All Articles