Skip to content
Advertisement

RegEx not matching all required chars. What did I do wrong?

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 then C or L, or
    • _L?| – a _ and then an optional L, or
    • (?:_X){0,3} – zero, one, two or three occurrences of _X substring
  • ) – end of the group
  • $ – end of string.
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement