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]*
The backslash \ is an escape character in Java Strings. That means backslash has a predefined meaning in Java. You have to use double backslash \\ to define a single backslash. If you want to define \w , then you must be using \\w in your regex.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With