Nikos Maravitsas

About Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

Validate IP Address with Java Regular Expression example

With this example we shall show you how to validate the format of ip addresses using Java Regular Expression. The basic format of ip addresses format policy is:

  • It must start with a number from 0 – 255.
  • It must be followed a dot
  • This pattern has to repeat for 4 times (eliminating the last dot…)

 
 
 
 
 
This is the regular expression used for ip address format validation:

^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$

You can take a look at the Pattern class documentation to learn how to construct your own regular expressions according to your policy.

1. Validator class

This is the class that we are going to use for ip address format validation.

IPAddressFormatValidator.java:

package com.javacodegeeks.java.core;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IPAddressFormatValidator{

    private Pattern pattern;
    private Matcher matcher;

    private static final String IPADDRESS_PATTERN = 
		"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
		"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
		"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
		"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";

    public IPAddressFormatValidator(){
	  pattern = Pattern.compile(IPADDRESS_PATTERN);
    }

    public boolean validate(final String ipAddress){		  
	  matcher = pattern.matcher(ipAddress);
	  return matcher.matches();	    	    
    }
}

2. Unit Testing our IPAddressFormatValidator class

For unit testing we are going to use JUnit. Unit testing is very important in these situations because they provide good feedback about the correctness of our regular expressions. You can test your program and reassure that your regular expression meets the rules on your policy about the form of the ip addresses.

This is a basic test class:

IPAddressFormatValidatorTest.java:

package com.javacodegeeks.java.core;

import static org.junit.Assert.*;

import java.util.Arrays;
import java.util.Collection;

import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class IPAddressFormatValidatorTest {

	private String arg;
	private static IPAddressFormatValidator iPAddressFormatValidator;
	private Boolean expectedValidation;

	public IPAddressFormatValidatorTest(String str, Boolean expectedValidation) {
		this.arg = str;
		this.expectedValidation = expectedValidation;
	}

	@BeforeClass
	public static void initialize() {
		iPAddressFormatValidator = new IPAddressFormatValidator();
	}

	@Parameters
	public static Collection<Object[]> data() {
		Object[][] data = new Object[][] {
				{ "192.102.100", false }, // must have a 4 '.' characters
				{ "a.b.c.d", false },     // you cannot have characters between '.'
				{ "1.2.3.800", false },   // you can have only until 255
				{ "1.2.3", false },       // you must have 4 digit parts

				{ "192.168.1.1",true },                         
				{ "10.10.10.10", true },
				{ "127.0.0.1", true } };

		return Arrays.asList(data);
	}

	@Test
	public void test() {
		Boolean res = iPAddressFormatValidator.validate(this.arg);
		String validv = (res) ? "valid" : "invalid";
		System.out.println("Hex Color Code "+arg+ " is " + validv);
		assertEquals("Result", this.expectedValidation, res);

	}

}

Ouput:

Hex Color Code 192.102.100 is invalid
Hex Color Code a.b.c.d is invalid
Hex Color Code 1.2.3.800 is invalid
Hex Color Code 1.2.3 is invalid
Hex Color Code 192.168.1.1 is valid
Hex Color Code 10.10.10.10 is valid
Hex Color Code 127.0.0.1 is valid

 
This was an example on how to validate IP Address with Java Regular Expression.

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close