user3299182 user3299182 - 6 months ago 27
Java Question

Regex to exclude certain wrong numbers pattern

I have an array of string in java that include good types of numbers:

String [] valid={"5","-1","0","0.0","8.0","1.5","0.7","-0.2","0.09","-0.15"};

And i have this regex to match and check if those are valid or not:

static boolean checkValidNum(String n){
return n.matches("^-?\\d+(\\.\\d+)?");

This regex is ok to check what is good and valid num but i want to exclude the following as valid nums:

String [] invalidNum = {"001","-00.2","-0","-0.0"};

What should i add to my regex to make it return false on those nums?


Provide some alternatives using |, e. g.

static boolean checkValidNum(String n) {
    return n.matches("^-?([1-9]\\d*(\\.\\d+)?|0\\.\\d*[1-9]\\d*)|0(\\.0)?");