Search code examples
javaregexstringgxt

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


Solution

  • 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.