Java Regex to Validate IPv4 Address Java Regex to Validate IPv4 Address

Page content

In this article, we’ll learn how to validate IPv4 addresses using Java Regex

IP Address Format

Let’s first take a look at typical IPv4 address examples:-

0.0.0.0
172.16.254.1
255.255.255.255
192.168.0.1
192.168.1.255

We have the following observations from the above examples:-

  1. A valid IPv4 Address is in the form of A.B.C.D
  2. The length of A, B, C, and D lies between 1 to 3 digits
  3. The value of A, B, C, and D lies between 0 to 255
  4. Leading 0’s not allowed

Regex to validate IP Address

^((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])\\.?\\b){4}$

Where,

  1. \\d to match single-digit numbers between 0 to 9
  2. [1-9]\\d to match numbers between 10 to 99
  3. 1\\d\\d to match numbers between 100 to 199
  4. 2[0-4]\\d to match numbers between 200 to 249
  5. 25[0-5] to match numbers between 250 to 255
  6. (\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]) to match numbers between 0 to 255
  7. \\.? to match the dot operator . after each number between 0 to 255
  8. \\b is a word boundary
  9. {4} to match 4 sets of such numbers (i.e. between 0 to 255)

We can further concise the above regex taking the common \\d out:-

^(((|[1-9]|1\\d|2[0-4])\\d|25[0-5])\\.?\\b){4}$

Validate IP address in Java

Let’s look at the Java method to validate the IPv4 addresses using the above regex:-

public static boolean validateIPv4Address(String ipv4){
  String regex = "^(((|[1-9]|1\\d|2[0-4])\\d|25[0-5])\\.?\\b){4}$";
  Pattern pattern = Pattern.compile(regex);
  Matcher matcher = pattern.matcher(ipv4);
  return matcher.matches();
}

Let’s use the above method to run test cases:-

  1. Test valid IPv4 addresses:-
    @Test
    public void validateIPv4Address_validIPv4Addresses(){
      assertTrue(validateIPv4Address("0.0.0.0"));  // pass
      assertTrue(validateIPv4Address("127.0.0.1")); // pass
      assertTrue(validateIPv4Address("192.168.10.1")); // pass
      assertTrue(validateIPv4Address("172.16.254.1")); // pass
      assertTrue(validateIPv4Address("192.168.1.255")); // pass
      assertTrue(validateIPv4Address("255.255.255.255")); // pass
      assertTrue(validateIPv4Address("10.98.30.56"));  // pass
    }
    
  2. Test invalid IPv4 addresses:-
    @Test
    public void validateIPv4Address_invalidIPv4Addresses(){
      assertFalse(validateIPv4Address("192.168.0.256")); // value above 255
      assertFalse(validateIPv4Address("192.168.0.01")); // leading 0 in 01
      assertFalse(validateIPv4Address("192.168.0")); // only 3 sets, 4th missing
      assertFalse(validateIPv4Address(".192.168.0.1")); // starts with .
      assertFalse(validateIPv4Address(".192.168.0.1.")); // ends with .
    }