javaregexregex-lookarounds

A regex to specify that the length of data should be either 12 or 14 but not 13


My regex requirement is the length of data should be either 12 or 14 but not 13.

Accordingly I created regex expression as ^[0-9]{12,14}$ .

It doesn't work.


Solution

  • You can make the last two numbers optional with the ? operator:

    String regex = "^[0-9]{12}([0-9]{2})?$";
    

    Also, [0-9] can be rewritten as \\d. This does the exact same thing:

    String regex = "^\\d{12}(\\d{2})?$";