Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Quantifiers {min,max} with Pipe (Or)

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}$/

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • "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})$/
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading