简体   繁体   中英

Validate number using regular expression in java

Can anyone help me for validation of numbers like:

1,478.25

Special characters like . And , are only allowed

(@#$_&-+()/ "':;!?~`|•√π÷׶={} not allowed )* .

This is the regex I have tried so far:

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

Your help will be appreciated. Valid number are 123.45 1,234.5 and 0.01

This is the regex you need: ^(\\\\d{1,3},)*(\\\\d{1,3})(.\\\\d{1,3})?$ along with the global and multiline flags.

This is how should be your code:

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

This is a live Demo .

Please use below regular expression to validate numeric value with one decimal and multiple comma

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

Please check this one.

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

^\d{1,}(,\d+)?\.\d+$

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM