I have to validate a string which can contain numbers from 1 to 7, and maximum length allowed is 7.
([1-7]){0,7}
Condition: No numbers should be repeated in the string.
eg:
12345 true;
11345 false (1 is repeated) ;
98014 false (0,8,9 are invalid);
This can be done in a single regex:
The lookahead assertion checks that all characters in the string are unique, and the actual regex only allows 0-7 digits between 1 and 7.
In Java:
Of course you can make the lookahead fail faster by replacing each
.with[1-7], but for clarity’s sake I’ve chosen not to. (And you can drop the^and$anchors if you use the.matches()method since they are implicit in that case).