How can I modify this regular expression to allow numbers with just one point?
/[^0-9\.]/g
It currently allows:
- 0
- 0.13
- 0.13.1 (this should not be allowable)
How can I modify this regular expression to allow numbers with just one point?
/[^0-9\.]/g
It currently allows:
- 0
- 0.13
- 0.13.1 (this should not be allowable)
- 1 There are so many similar questions linked on the right of this page. Didn't you see them when you were writing your question ? – Denys Séguret Commented Aug 9, 2013 at 14:35
- 1 You don't need to escape a dot in a character class – HamZa Commented Aug 9, 2013 at 14:36
- @dystroy, I did thorough search before posting, but none provided satisfiable answer. and none on the right point to what i am asking – Abhishek Madhani Commented Aug 9, 2013 at 14:38
- stackoverflow./questions/10169147/… – Denys Séguret Commented Aug 9, 2013 at 14:44
- Trying to find the duplicate, but this one is closed. Does it answer your question? Can you figure it out from the (pretty good) explanation there? – Ry- ♦ Commented Aug 9, 2013 at 14:46
6 Answers
Reset to default 12Your regex doesn't matches what you say it matches. You have used negation in character class, and that too without any quantifier. Currently it would match any non-digit character other than .
.
For your requirement, you can use this regex:
/^\d+(\.\d+)?$/
Make the match a positive one:
/^\d*(\.\d+)?$/
Any number of digits, optionally followed by a point and at least one digit. But it’s not worth it to keep a negative match.
If you want to disallow an empty string (which the original regular expression wouldn’t do), you could do this:
/^(?=.)\d*(\.\d+)?$/
But you could also just check for an empty string, which looks better anyways.
I guess this should do /^(\d*)\.{0,1}(\d){0,1}$/
OR /^(\d*)\.?(\d){0,1}$/
(\d*)
Represents number of digits before decimal.\.
followed by{0,1}
OR?
will make sure that there is only one dot.(\d){0,1}
Allows only one digit after decimal.
You can try the following regex ^[-+]?\d*.?\d*$
Try,
(value.match(/^\d+([.]\d{0,1})?$/))
Try the following:
/^(\d*)(\.\d*)?$/g