Java Regular Expressions - Validate IP Addresses

Check if IP Address is Valid Or Not with Java

Regular Expressions are widely-applicable and used to match patterns in text, whether for search, validation or other processing.

A common way to use them is to check whether a number is valid - i.e. follows a pattern. IP addresses follow a particular pattern, and can be tested with Regular Expressions.

This can also include validating Subnet masks, country-specific IPs, or any other criteria. In this example, we are just checking if a number is a valid IP or not:

public class RegexTutorial {
   public static void main(String[] args) {
       // Looking for a valid IP Address.
       Pattern pattern = Pattern.compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
       Matcher matcher = pattern.matcher("192.168.1.1");
       boolean match = matcher.matches();
       System.out.println(match);
    }
}

The output will be:

true
Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

This is a valid IP Address since this matches our criteria of 4 numbers separated by dots. All numbers are within the range of a valid IP Address too:

public class RegexTutorial {
    public static void main(String[] args) {
       // Looking for a valid IP Address.
        Pattern pattern = Pattern.compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
        Matcher matcher = pattern.matcher("400.168.1.1");
        boolean match = matcher.matches();
        System.out.println(match);
    }
}

The output will be:

false

This is invalid since 400 is out of our IP Address range.

Follow to keep up with AI and the future of software

Practical takes on AI, tooling, and where development is headed.

Last Updated: January 20th, 2023
Was this helpful?

Make Clarity from Data - Quickly Learn Data Visualization with Python

Learn the landscape of Data Visualization tools in Python - work with Seaborn, Plotly, and Bokeh, and excel in Matplotlib!

From simple plot types to ridge plots, surface plots and spectrograms - understand your data and learn to draw conclusions from it.

© 2013-2026 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms