Reputation: 2691
I stuck in a regex, where I need to create regex
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
Reputation: 784998
You can use this regex:
^[SEC](?:,[SEC]){0,2}$
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
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