How to Find or Validate an IP Address in Java


In this example, we will learn how to validate IP address using regular expressions including encapsulation of the rule into a Pattern object, and a matcher for a judgment.

Source Code

package com.beginner.examples;

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

public class ValidateIPAddressExample {

	public static void main(String[] args) {

		String ip1 = "192.168.2.14";

		String ip2 = "10.233.88.10";

		String ip3 = "10.3333.4.8";
		
		//Encapsulate rules as objects
		Pattern pattern = Pattern.compile("(d{1,3}.){3}d{1,3}");

		//Determine whether ip1 conforms
		//Get the matcher from Pattern
		Matcher m1 = pattern.matcher(ip1);
		//Use the matchers() method in the Matcher to see if this fits
		System.out.println("ip1 :" + m1.matches());
		
		//Determine whether ip2 conforms
		Matcher m2 = pattern.matcher(ip2);
		System.out.println("ip3 :" + m2.matches());
		
		//Determine whether ip3 conforms
		Matcher m3 = pattern.matcher(ip3);
		System.out.println("ip3 :" + m3.matches());

	}

}

Output:

ip1 :true
ip3 :true
ip3 :false

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments