I am struggling with java regex. I want to validate if a number is greater than zero and it should not be negative also
0.00011 - GOOD
1.222 - GOOD
0.000 - BAD
-1.1222 - BAD
So anything above zero is okay. Is this possible in java regex?
Don't do this with regexes. Do this with BigDecimal
:
// True if and only if number is strictly positive
new BigDecimal(inputString).signum() == 1
Why regex?
You can simply do something like following
double num=0.00011;
if(num>0){
System.out.println("GOOD");
}else{
System.out.println("BAD");
}
Or if you rally want to do this in hard way you can try some thing as follows too
String num="-0.0001";
char sign=num.split("\\.")[0].charAt(0);
if(sign=='-' || Double.parseDouble(num)==0.0){
System.out.println("BAD");
}else {
System.out.println("GOOD");
}
It is better not to solve it using regex, still here is one of the solution how to solve it using regex:
public static void main (String[] args) throws java.lang.Exception
{
String str = "0.0000";
Pattern p = Pattern.compile("(^-[0-9]+.+[0-9]*)|(^[0]+.+[0]+$)");
Matcher m = p.matcher(str);
if (m.find()) {
System.out.println("False");
}else{
System.out.println("True");
}
}
Here is the demo
Try
^(0\\.\\d*[1-9]\\d*)|([1-9]\\d*(\\.\\d+)?)$
Which will match
0.1
0.01
0.010
0.10
1.0
1.1
1.01
1.010
3
but not
0
0.0
-0.0
-1
-0.1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.