Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Here is my @Pattern annotation. I want to disallow digits that repeat 9 times. What have I done wrong?

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

These would be invalid strings:

111111111
222222222

These would be valid:

111111112
222222221
123456789

Only strings with a length of 9 will be valid but this is not needed as part of the regular expression since that will be controlled by other annotations.

like image 658
coder Avatar asked Oct 12 '22 01:10

coder


1 Answers

Edited following the comments

I think you meant you don't want the same digit repeating 9 times. To do that, you need to capture one digit, and refer to that and see if it repeats for 8 more times.

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

If you simply use \\d{9}, it will mean repeatition of any digits.

Note also that you don't need .*. Regex will decide where to start the match on its own.

like image 101
sawa Avatar answered Dec 07 '22 22:12

sawa