validate ip address java

Java Regular Expressions Validate IP Addresses: A Guide to Pattern Matching and Verification

In Java, you can determine the validity of an IP address by utilizing Regular Expressions (regex) to match the address against a prescribed pattern. An IP address is deemed valid when it consists of four numerical segments separated by periods, with each segment ranging from 0 to 255.

Here’s an example of how you can apply a regex pattern for IP address validation:

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

public class IPValidation {
    public static boolean isValidIPAddress(String ip) {
        String ipRegex = "^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
        Pattern pattern = Pattern.compile(ipRegex);
        Matcher matcher = pattern.matcher(ip);
        return matcher.matches();

When this method is executed, it will return a boolean value:

  • True: Indicates the IP address adheres to the expected format and falls within the valid numerical range.
  • False: Shows that the IP address, such as 400.168.1.1, does not comply due to the first segment surpassing the upper limit of 255.

For instance:

System.out.println(isValidIPAddress(""));  // Output: true
System.out.println(isValidIPAddress("400.168.1.1"));  // Output: false

Understanding and implementing regex for IP validation is essential for anyone dealing with network-based Java applications. This is where ensuring the correctness of IP addresses is crucial.

Posted by
Glenn Yang

I code in Python, JavaScript, and C++; Open-source advocate; Hackathon participant and 'con enjoyer.