I’d like a regex that is either X or Y characters long. For example, match a string that is either 8 or 11 characters long. I have currently implemented this like so: ^([0-9]{8}|[0-9]{11})$.
I could also implement it as: ^[0-9]{8}([0-9]{3})?$
My question is: Can I have this regex without duplicating the [0-9] part (which is more complex than this simple \d example)?
There is one way:
or alternatively, if you want to do the length check first,
That way, you have the complicated part only once and a generic
.for the length check.Explanation: