javaregexdecimal-point

Regex Pattern validation in Java to match 2 decimal points


I need to validate a number pattern with 2 decimal points with after each decimal point it can contain only up to 2 digits. It can contain a whole number only up to 4 digits.

Ex: maximum value it can insert is in this format yyyy.yy.yy

 yyyy - allow without any decimal places
   yyyy.y - allow
   yyyy.y.y - allow

yyyy.yyy.yy - can't allow (Since this has 3 digits after 1 decimal point) yyyy.yy.yyy - can't allow (Since this has 3 digits after 2 decimal point)

yyyy.y.yy  - (Allow)
yyyy.yy.y  - (Allow)

yyyy.yy.y - (Allow)

bold part only allow up to 4 digits.

Currently if i use this validation ^[0-9]{1,4}(\\.[0-9]{0,2})?$
This validation works for this correctly.

yyyy.yy - maximum value

But I want to validate this yyyy.yy.yy.If i use ^[0-9]{1,4}(\\.[0-9]{0,2})(\\.[0-9]{0,2})?$
for this yyyy.yy.yy It doesn't work properly.


Solution

  • Your regex contains duplication. You can add quantifier to second group. Try this regex

    ^\d{1,4}(\.\d{0,2}){0,2}$
    

    Demo

    Java example

    public static void main(String[] args) {
        String[] arr = new String[] {"1234", "1234.1.2", "1234.22.22", "1234.2", "1.2.3", // all match
                                     "5.555.5", "55555", "5.55.555"}; // all don't match
    
        for(String s : arr) {
            if(s.matches("^\\d{1,4}(\\.\\d{0,2}){0,2}$")) {
                System.out.println(s);
            }
        }
    }
    

    Output

    1234
    1234.1.2
    1234.22.22
    1234.2
    1.2.3