I want to allow inputs like _X_C or _X_X_X with the following regex:
^(_X_C|_X_L|_L?)((_X){0,3})$
The following should be allowed only once:
- _X_C
- _X_L
- _L
or …
- _X_X_X (0 to threetimes)
The only thing that does not work is the allowance of “_X_X_X” or even “_X”
What did I do wrong?
Advertisement
Answer
You may use
^(?:_X_C|_X_L|_L?|(?:_X){0,3})$
^(?:_X_[CL]|_L?|(?:_X){0,3})$
See the regex demo.
Details:
^– start of string(?:– start of a non-capturing group:_X_[CL]|–_X_and thenCorL, or_L?|– a_and then an optionalL, or(?:_X){0,3}– zero, one, two or three occurrences of_Xsubstring
)– end of the group$– end of string.