DEV Community

Kenneth Lum
Kenneth Lum

Posted on

2

In JavaScript or PCRE regular expression, you have to specify a `0` for a minimum quantity

If we try to match "3 characters or more" in JavaScript:

> "abcde".match(/.{3,}/)
[ 'abcde', index: 0, input: 'abcde', groups: undefined ]

> "ab".match(/.{3,}/)
null
Enter fullscreen mode Exit fullscreen mode

But if we want to do "3 characters or less" (or 80 characters or less, to look for short lines), we can't omit the "lower bound" of the range. We have to supply a 0 in {0,3} or {0,80}:

> "abcde".match(/.{0,10}/)
[ 'abcde', index: 0, input: 'abcde', groups: undefined ]

> "abcde".match(/.{,10}/)
null
Enter fullscreen mode Exit fullscreen mode

If you are used to writing regular expressions in Python or Ruby, you actually can omit the lower bound, and if you make it a habit, you may wonder why it doesn't work in JavaScript or in Bash's grep using PCRE mode. So remember to always put in that 0.

You may wonder, then what does .{,3} match? The answer is: verbatim

> "a{,3}".match(/.{,3}/)
[ 'a{,3}', index: 0, input: 'a{,3}', groups: undefined ]
Enter fullscreen mode Exit fullscreen mode

The a matches the ., and the {,3} is matched "verbatim".

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more