Reputation: 53
I read a lot of regex question, but I didn't find this yet..
I want a regex in Java to check whether a string (no limit to length) is a number:
including negative (-4/-123)
including 0
including positive (2/123)
excluding +
(+4/+123)
excluding leading zero 0
(05/000)
excluding .
(0.5/.4/1.0)
excluding -0
This is what I have done so far:
^(?-)[1-9]+[0-9]*
Upvotes: 5
Views: 9852
Reputation: 82461
The is a optional -
-?
The number must not start with a 0
[1-9]
it may be followed by an arbitraty number of digits
\d*
0 is an exception to the "does not start with 0 rule", therefore you can add 0 as alternative.
Final regex
-?[1-9]\d*|0
java code
String input = ...
boolean number = input.matches("-?[1-9]\\d*|0");
Upvotes: 12