Shekhar Khairnar Shekhar Khairnar - 16 days ago 4
Java Question

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

Answer

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