有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java正则表达式,仅适用于不包括零的正数

我正在努力使用java正则表达式。 我想验证一个数字是否大于零,它也不应该是负数

0.00011 - GOOD
1.222 - GOOD
0.000 - BAD
-1.1222 - BAD

所以任何高于零的都可以。 这在java正则表达式中可能吗


共 (4) 个答案

  1. # 1 楼答案

    最好不要使用正则表达式来解决这个问题,下面是一个使用正则表达式解决这个问题的方法:

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

    这是demo

  2. # 2 楼答案

    为什么是正则表达式

    你可以简单地做如下事情

     double num=0.00011;
        if(num>0){
            System.out.println("GOOD");
        }else{
            System.out.println("BAD");
        }
    

    或者,如果你想以艰难的方式做到这一点,你也可以尝试以下几点

     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");
       }
    
  3. # 3 楼答案

    试试看

    ^(0\\.\\d*[1-9]\\d*)|([1-9]\\d*(\\.\\d+)?)$
    

    哪个匹配

    0.1
    0.01
    0.010
    0.10
    1.0
    1.1
    1.01
    1.010
    3
    

    但不是

    0
    0.0
    -0.0
    -1
    -0.1
    
  4. # 4 楼答案

    不要对正则表达式这样做。使用BigDecimal执行此操作:

    // True if and only if number is strictly positive
    new BigDecimal(inputString).signum() == 1