Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - regex for ordinary positive negative number

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]*
like image 413
J. Doe Avatar asked Dec 13 '16 18:12

J. Doe


People also ask

What does \\ mean in Java regex?

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.


1 Answers

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");
like image 118
fabian Avatar answered Oct 28 '22 06:10

fabian