ct2602
ct2602

Reputation: 95

How to reject repetition of character within Java regular expression

I am looking for help with a Java regular expression please.

My regular expression should accept a string of length 5 only, with characters matching [BDILMOP] only.

No repeated characters are allowed - eg. BDILM is allowed, but BDILL or BDLLL are not.

Please help - I'm new to regex and so would appreciate any advice that you could throw my way.

Thanks!

Upvotes: 0

Views: 375

Answers (1)

anubhava
anubhava

Reputation: 784998

You can use this negative lookahead based regex:

^(?!.*(.).*\1)[BDILMOP]{5}$

(?!.*(.).*\1) is negative lookahead which fails the match if there is any repetition in input. (.) captures a letter in group #1 and \1 is back-reference of the same group thus checking repetition.

RegEx Demo

Upvotes: 1

Related Questions