使用java中的正则表达式验证数字

问题描述 投票:-5回答:3

任何人都可以帮助我验证数字,如:

1,478.25

.,这样的特殊角色是允许的

(@#$ _& - +()/“':;!?~` |•√π÷׶= {}不允许)*。

这是我到目前为止尝试过的正则表达式:

/^[0-9]+([,][0-9]+)?$/

我们将不胜感激。有效数字为123.45 1,234.5和0.01

java regex string gxt
3个回答
0
投票

请使用下面的正则表达式来验证带有一个小数和多个逗号的数值

      String num="1,335.25";

        String exp ="^[-+]?[\\d+([,]\\d+)]*\\.?[0-9]+$";

        if(num.matches(exp)){  
            System.out.println("valid number");
        }else{
            System.out.println("Not a valid number");
        }

请检查一下。


0
投票

这是你需要的正则表达式:^(\\d{1,3},)*(\\d{1,3})(.\\d{1,3})?$以及globalmultiline标志。

这是你的代码应该如何:

final String regex = "^(\\d{1,3},)*(\\d{1,3})(\\.\\d{1,3})?$";
final String string = "1,478.25\n"
     + "1,450\n"
     + "48.10\n"
     + "145.124.14";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);


while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
}

这是a live Demo


0
投票

我认为这个正则表达式就是你所需要的

^\d{1,}(,\d+)?\.\d+$
© www.soinside.com 2019 - 2024. All rights reserved.