java regex pattern validate ip address

Regular expressions

Regular expressions represents a sequence of symbols and characters expressing a string or pattern to be searched for within a longer piece of text. The abbreviation for regular expression is regex. In programming regular expressions are mainly used to define constraint on strings like password, email validation.

Regular expression ip address 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])$

This regular expression refers to a pattern with digit from 0 to 255 and follow by a dot “.”, repeat 4 time and ending with no dot “.”

Example

package com.w3schools;
 
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class RegexTest {
	private static final String 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 static void main(String args[]){ 
		List<String> values = new ArrayList<String>();	
		values.add("255.255.255.255"); 
		values.add("127.0.0.1"); 
		values.add("10.10");
		values.add("10.10.10.256");
 
		Pattern pattern = Pattern.compile(PATTERN);
		for (String value : values){
		  Matcher matcher = pattern.matcher(value);
		  if(matcher.matches()){
			  System.out.println("IP "+ value +" is valid");
		  }else{
			  System.out.println("IP "+ value +" is invalid");
		  }		  
		}
	}
}

Output

IP 255.255.255.255 is valid
IP 127.0.0.1 is valid
IP 10.10 is invalid
IP 10.10.10.256 is invalid