javaregexstring

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:

This is what I have done so far:

^(?-)[1-9]+[0-9]*

Solution

  • 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");