Shekhar Khairnar
Shekhar Khairnar

Reputation: 2691

Regex three letters separated by comma and no repeating letters

I stuck in a regex, where I need to create regex

  1. Which can have max three given letters
  2. Three letters should be separated by comma
  3. If single letter is there no comma
  4. and comma should be not count
  5. Letter should not be repeat

Example: Three letter will be S,E,C

regex should match:

S
S,E
S,C
S,E,C
E,C
C

should not match:

S,S
S,E,E,C
S,E,C,C
S,E,C,S
S,E,C,E,S

I have tried this regex:

^[SEC]{1,3}$

but I can't figure out how to exclude repeating letters and how to include comma and not count comma

Thanks

Upvotes: 2

Views: 334

Answers (2)

anubhava
anubhava

Reputation: 784998

You can use this regex:

^[SEC](?:,[SEC]){0,2}$

RegEx Demo

This regex allows one of S,E,C at start followed by comma separated same group of letter 0 to 2 times.

If you want all unique letters only use:

^([SEC])(?:,(?!\1|\2)([SEC])){0,2}$

Upvotes: 2

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

The character class [SCE] will match either S, or C, or E.

Then, to match zero, one or two sequences of a comma and one of the 3 allowed chars, you need a grouping construct: (,[SCE]){0,2} or, with a non-capturing grouping construct, (?:,[SCE]){0,2}.

To make sure there are no repeating chars, use a negative lookahead anchored at the start that will fail the match once the same char is found - ^(?!.*([SCE]).*\1) - where ([SEC]) is Group 1 and \1 is the backreference referring to the value captured in this group (either S, E, C)

Use

^(?!.*([SCE]).*\1)[SCE](?:,[SCE]){0,2}$ 

See the regex demo

Upvotes: 2

Related Questions