【问题标题】:regex for validation of positve numbers including zeros and 2 places after decimal in java?正则表达式用于验证Java中的正数,包括零和小数点后2位?
【发布时间】:2013-08-23 13:49:25
【问题描述】:
("^\d{1,15}(\.\d{1,2})?$") 

这是我正在尝试使用的正则表达式,但 java 给出了语法错误。

^(?!(?:0|0\.0|0\.00)$)[+]?\d+(\.\d|\.\d[0-9])?$

这对于 00.00、124.03、0.13 等数字很有效,但不适用于 0.0 和 0。

请修改正则表达式,使其接受以下类型的数字:

123456.00,
12415366.88,
0.23,
0,
0.00,
0.0,
432547,

即仅包含零和小数点后 2 位的正数

【问题讨论】:

  • This 问题的可能重复项,除非您必须对 0 进行一些修改。
  • 第一个示例中的编译错误可以通过将\d 中的反斜杠正确转义为\\d 来修复。第二个正则表达式明确排除了00.00.00。在此处提出问题之前,您应该尝试理解您的代码。
  • 为什么需要使用正则表达式?试试这样的stackoverflow.com/questions/50532/…

标签: java regex


【解决方案1】:

您的第一个正则表达式是最好的,但请记住,在 java 中您必须使用 double 反斜杠来编码文字反斜杠,因此:

str.matches("\\d{1,15}(\\.\\d{1,2})?") 

请注意,对于 matches(),您不需要前导 ^ 或尾随 $,因为表达式必须匹配整个字符串才能返回 true。

语法错误可能是因为\d 不是有效的转义序列,而\n 等是有效的。

【讨论】:

    【解决方案2】:

    公共类 RegexTest {

    public static void main(String[] args) {
        String regexExpression = "([0-9]+[.]?|[0-9]*[.][0-9]{0,2})";
    
        // True examples
        System.out.println("123456.00".matches(regexExpression));
    
        System.out.println("12415366.88".matches(regexExpression));
    
        System.out.println("0".matches(regexExpression));
    
        System.out.println("0.0".matches(regexExpression));
        System.out.println("0.00".matches(regexExpression));
        System.out.println("432547".matches(regexExpression));
    
        System.out.println("00.00".matches(regexExpression));
    
        System.out.println("124.03".matches(regexExpression));
    
        // False examples
        System.out.println("124.033".matches(regexExpression));
        System.out.println("-124.03".matches(regexExpression));
    }
    

    }

    【讨论】:

    • 匹配1.,匹配.2,也匹配.! :)
    【解决方案3】:

    我不知道为什么在这里使用正则表达式。你可以这样试试

      String num="253.65";
        try{
            double d=Double.parseDouble(num);
            if(d==0.0){
                System.out.println("valid");
            }else if(d>0&&(num.split("\\.")[1].length()==2)){
                System.out.println(num+" is valid");
            }else{
                System.out.println(num+" is invalid");
            }
        } catch (NumberFormatException e){
            System.out.println(num+"is not a valid number");
        }
    

    直播Demo

    【讨论】:

    • 如果不是双精度的有效字符串表示,将抛出异常。
    • 此时,正则表达式提供了一个更加清晰和紧凑的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2015-04-21
    • 2012-01-22
    • 2022-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    相关资源
    最近更新 更多