Search code examples
javaregexstringpattern-matchingregular-language

Regular Expression inner Digits check


I have the following regex but it fails (the inner digits with the points) :

([0-9]{1,3}\.?[0-9]{1,3}\.?[0-9]{1,3})

I want that it covers the following cases:

  • 123 valid
  • 123.4 valid
  • 123.44 valid
  • 123.445 valid
  • 123.33.3 not ok (regex validates it as true)
  • 123.3.3 not ok (regex validates it as true)
  • 123.333.3 valid
  • 123.333.34 valid
  • 123.333.344 valid

Can you please help me?


Solution

  • You have multiple case, I would like to use | the or operator like this :

    ^([0-9]{1,3}|[0-9]{1,3}\.[0-9]{1,3}|[0-9]{1,3}\.[0-9]{3}\.[0-9]{1,3})$
    ^           ^                      ^                                 ^
    

    you can check the regex demo


    details

    The regex match three cases :

    case 1

    [0-9]{1,3}
    

    this will match one or more digit

    case 2

    [0-9]{1,3}\.[0-9]{1,3}
    

    this will match one or more digit followed by a dot then one or more digits

    case 3

    [0-9]{1,3}\.[0-9]{3}\.[0-9]{1,3}
    

    this will match one or more digit followed by a dot then three digits then a dot then one or three digits

    Note you can replace [0-9] with just \d your regex can be :

    ^(\d{1,3}|\d{1,3}\.\d{1,3}|\d{1,3}\.\d{3}\.\d{1,3})$