jimcgh
jimcgh

Reputation: 5957

Checking if a string contains unique characters from a particular set

I want a string to consist of unique characters from the set [a,i,b,w].A string should consist of atleast 1 and max 4 characters from this set only but the characters cannot repeat and any permutation is allowed. So for example aa or bwaw is not allowed. Can i use a regex to test this or do i need to parse it myself in code ?

Thank You

Upvotes: 1

Views: 320

Answers (1)

nhahtdh
nhahtdh

Reputation: 56819

For a (mathematical) set of characters (no two occurrences of the same character in a set, as opposed to a multiset, which allows multiple occurrences), you can construct the regex based on the following template:

^(?!.*(.).*\1)[<set_of_characters>]{1,<cardinality_of_character_set>}$

For example, in your case:

^(?!.*(.).*\1)[abiw]{1,4}$

(?!.*(.).*\1) is zero-width negative look-ahead, that check whether you can find any repeating character in the text ahead .*(.).*\1. This uses the assumption stated above that the characters must not appear twice in the input string.

[abiw]{1,4} is just simply 1 to 4 occurrences of any of the characters [abiw]. Since we have checked that the string does not contain any repeating character with the negative look-ahead above, this part simply check that the string consists of only the characters in the specified set.

Upvotes: 3

Related Questions