How to Validate IP Address with Regular Expression in Java


In this example we will show how to validate IP address with regular expression in Java.

Source Code

package com.beginner.examples;

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

public class ValidateIP {

	public static void main(String[] args) {
		String oneAddress = "10.127.30.45"; 
		String twoAddress = "127.30.45";
		String threeAddress = "255.255.255.2567";
		
		System.out.println(isIP(oneAddress));
		System.out.println(isIP(twoAddress));
		System.out.println(isIP(threeAddress));
	}
	
	public static boolean isIP(String addr){  
		if(addr.length()  15 || "".equals(addr))
		{  
			return false;
		}
		String rexp = "([1-9]|[1-9]d|1d{2}|2[0-4]d|25[0-5])(.(d|[1-9]d|1d{2}|2[0-4]d|25[0-5])){3}";  
		Pattern pat = Pattern.compile(rexp);     
		Matcher mat = pat.matcher(addr);    
		boolean ipAddress = mat.find();  
		return ipAddress;  
	}
}

Output:

true
false
false

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

How to Validate IP Address with Regular Expression in Java


In this example we will show how to validate IP address with regular expression.

Source Code

package com.beginner.examples;

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

public class ValidateIP {

	public static void main(String[] args) {
		String oneAddress = "10.127.30.45"; 
		String twoAddress = "127.30.45";
		String threeAddress = "255.255.255.2567";
		
		System.out.println(isIP(oneAddress));
		System.out.println(isIP(twoAddress));
		System.out.println(isIP(threeAddress));
	}
	
	public static boolean isIP(String addr){  
		if(addr.length()  15 || "".equals(addr))
		{  
			return false;
		}
		String rexp = "([1-9]|[1-9]d|1d{2}|2[0-4]d|25[0-5])(.(d|[1-9]d|1d{2}|2[0-4]d|25[0-5])){3}";  
		Pattern pat = Pattern.compile(rexp);     
		Matcher mat = pat.matcher(addr);    
		boolean ipAddress = mat.find();  
		return ipAddress;  
	}
}

Output:

true
false
false

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments