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
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
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 ]
The a
matches the .
, and the {,3}
is matched "verbatim".
Top comments (0)