REGEXVAULTv2.0
Security/Network Security
Verified Safe

CIDR Notation (IPv4) Regex for Java

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

What this pattern does

This page provides a comprehensive, battle-tested regular expression for matching cidr notation (ipv4), ported and verified for Java. In security-sensitive code, using an unverified regex can open the door to both false positives and denial-of-service attacks. The snippet below is ready to drop into your Java project — whether you're validating in a Spring Boot controller, a Jakarta EE service, or a standalone utility class.

Java Implementation

Java
// CIDR Notation (IPv4)
// ReDoS-safe | RegexVault — Security > Network Security

import java.util.regex.Pattern;

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

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

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

Test Cases

Matches (Valid)
Rejects (Invalid)
192.168.1.0/24192.168.1.0/33
10.0.0.0/8192.168.1.0/-1
172.16.0.0/12192.168.1.0
0.0.0.0/0256.0.0.0/8
1.2.3.4/32192.168.1.0/24/extra

When to use this pattern

This pattern is drawn from the Security > Network Security category and carries a ReDoS-safe certification. That matters for Java developers because critical in Java applications since the JVM regex engine uses backtracking and is susceptible to ReDoS without careful pattern design. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.

Common Pitfalls

0.0.0.0/0 (any IP) in a security group rule exposes a service to the entire internet. 0.0.0.0/0 in outbound rules allows all outbound traffic. Review CIDR rules regularly in cloud security groups.

Technical Notes

/0 = all IPs (default route), /32 = single host. Subnets should have a host part of all zeros for canonical CIDR notation (192.168.1.0/24, not 192.168.1.5/24). Common in firewall rules, security groups, and IP allowlists.

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