How to Find or Validate an IP Address in Java

In this example we will show 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 = "";

		String ip2 = "";

		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());




ip1 :true
ip3 :true
ip3 :false


Imported packages in Java documentation:

Notify of
Inline Feedbacks
View all comments