I want to match a number with 1 to 4 digits which doesn't start with 0, using a regular expression in JavaScript. I tried:
^[^0]\d{1,4}$
But this doesn't work.
Is there any problem with {1,4}
in JavaScript?
It should check digits are matched 1 to 4 times, shouldn't it?
I want to match a number with 1 to 4 digits which doesn't start with 0, using a regular expression in JavaScript. I tried:
^[^0]\d{1,4}$
But this doesn't work.
Is there any problem with {1,4}
in JavaScript?
It should check digits are matched 1 to 4 times, shouldn't it?
-
2
[^0]
means - any character other than0
– zerkms Commented Jun 5, 2015 at 8:07 -
^\d{1,4}$
should work for you. Tested with regexpal. – nilsK Commented Jun 5, 2015 at 8:09 - @nilsK and i don't want first digit be 0 – Peyman abdollahy Commented Jun 5, 2015 at 8:12
- 1 Please be more precisely with your questions. Take your time, the people answering your question are doing it too. No offense, but if you are asking yourself why you got down votes, this might be your anser. – nilsK Commented Jun 5, 2015 at 8:32
3 Answers
Reset to default 7Why your regex doesn't work
^[^0]\d{1,4}$
means anything apart from 0 followed by 1 to 4 digits. Therefore the following will match:
- A6789
- Z0
The solution
If you want any 1 to 4 digit number but without starting 0s you want:
^(?!0)\d{1,4}$
This will match:
- 1234
- 5
- 99
But not:
- 0123
- 005
- 12345
- Z123
Why the solution works
(?!0)
is a Negative Lookahead which asserts the string doesn't start with the contained pattern, in this case 0
.
Your regex is incorrect. There is no problem in Javascript.
Here is the regex you want:
^[1-9]\d{0,3}$
Basically:
[1-9]
matches any number that isn't0
\d{0,3}
will match up to 3 more numbers, from 0 to 9
The regex you have will match these:
Z000
.123
-111
- ...
Please show us the code that does not work.
This is what you are doing now:
- One character that is not
0
- One to four characters that are decimal numbers
So you can produce 5 digits. Yout gotta correct that. We can help you if you provide code and context.