REGEXVAULTv2.0
Web & Network/IPv4
Verified Safe

IPv4 Address (Strict 0–255) Regex for Java

/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])$/

What this pattern does

This Java regex precisely validates IPv4 addresses, enforcing strict octet ranges from 0 to 255. Accurately parsing IP addresses is essential to prevent vulnerabilities and ensure correct network configuration, making this pattern critical for data validation. This pattern is ideal for use in Java-based network applications, custom data parsers, or any project requiring secure and reliable IP address validation.

Java Implementation

Java
// IPv4 Address (Strict 0–255)
// ReDoS-safe | RegexVault — Web & Network > IPv4

import java.util.regex.Pattern;

public class Ipv4AddressStrict0255Validator {
    private static final Pattern PATTERN =
        Pattern.compile("^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])$");

    public static boolean validate(String input) {
        return PATTERN.matcher(input).matches();
    }

    // Example
    public static void main(String[] args) {
        System.out.println(validate("0.0.0.0")); // true
    }
}

Test Cases

Matches (Valid)
Rejects (Invalid)
0.0.0.0256.1.1.1
192.168.1.1192.168.1
255.255.255.255192.168.1.1.1
10.0.0.1192.168.01.1
172.16.254.1not.an.ip.addr

When to use this pattern

ReDoS vulnerabilities pose a significant risk in Java applications due to the backtracking behavior of the built-in regex engine. Without a carefully designed pattern, a malicious actor can craft input that causes excessive backtracking, leading to denial-of-service. Imagine this regex used within a Spring Security configuration or an API gateway. With this ReDoS-safe pattern, you can confidently validate IP addresses in production, knowing your application is protected against this class of attack.

Common Pitfalls

Using \d{1,3} instead of the strict alternation allows values like 999 or 256. Do not use [0-9]{1,3} — it accepts out-of-range octets.

Technical Notes

The alternation order in each octet group (25[0-5] first, then 2[0-4], then 1xx, then [1-9][0-9], then single digit) is critical for correctness. Reordering breaks range enforcement. Leading zeros are rejected because 01 does not match any branch.

Have a pattern that belongs in the vault?

Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.

Submit a Pattern