Reputation: 13
Currently I am trying to find a regular expression, that does the following
1) checks number
2) Allows max length of 3
3) Does not start with 0
I have the following regex which works fine
^[0-9]{1,3}$
Above regular expression allows only numbers that have maximum 3 digits but I am not sure how to prevent 0 in the beginning.
code
var numericRegex = new RegExp("^[1-9][0-9]{0,2}$");
numericRegex.test(123) //false
Let me know what I am missing
Thanks
Upvotes: 1
Views: 733
Reputation: 2182
Try it like this:
^[1-9][0-9]?[0-9]?$
or:
^[1-9][0-9]{0,2}$
In node.js it can be used like this:
> "123".match(/^[1-9][0-9]{0,2}$/)
[ '123', index: 0, input: '123' ]
> "023".match(/^[1-9][0-9]{0,2}$/)
null
> "123".match(/^[1-9][0-9]?[0-9]?$/)
[ '123', index: 0, input: '123' ]
> "023".match(/^[1-9][0-9]?[0-9]?$/)
null
And the other answer is also fine:
> "123".match(/^(?!0)\d{1,3}$/)
[ '123', index: 0, input: '123' ]
> "023".match(/^(?!0)\d{1,3}$/)
null
Upvotes: 2