I am a bit confused at the moment because I cannot explain the following behaviour. Quantifiers {min,max} in dependency with a pipe (or) seem to have a different function. Why?
/^[a-z]{2,4}|[0-9]{2,6}$/
- "a" (no match)
- "ab" (match)
- "abcd" (match)
- "abcdef" (match)
- "1" (no match)
- "12" (match)
- "1234" (match)
- "123454678" (match)
/^[a-z]{2,4}$/
- "a" (no match)
- "ab" (match)
- "abcd" (match)
- "abcdef" (no match)
Thanks a lot!
>Solution :
Your problem is that the pipe has a lower binding than the anchors. When you have
/^[a-z]{2,4}|[0-9]{2,6}$/
the pipe for "or" binds differently than you expect. It basically means
/^[a-z]{2,4} OR [0-9]{2,6}$/
So you’re matching "beginning of string followed by 2-4 letters" or "2-6 digits followed by the end of the string.
If you’re trying to do "the entire string must be either 2-4 letters, or 2-6 digits", then you have to do:
/^([a-z]{2,4}|[0-9]{2,6})$/