REGEXVAULTv2.0
Security/Network Security
Verified Safe

CIDR Notation (IPv6) Regex for Java

/^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\/(?:1[01][0-9]|12[0-8]|[0-9]{1,2})$|^::(?:[fF]{4}(?::0{1,4})?:)?(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})){3}\/(?:1[01][0-9]|12[0-8]|[0-9]{1,2})$|^(?:[0-9a-fA-F]{0,4}:){1,7}(?::[0-9a-fA-F]{0,4}){0,7}\/(?:1[01][0-9]|12[0-8]|[0-9]{1,2})$/i

What this pattern does

This page provides a comprehensive, battle-tested regular expression for matching cidr notation (ipv6), 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 (IPv6)
// ReDoS-safe | RegexVault — Security > Network Security

import java.util.regex.Pattern;

public class CidrNotationIpv6Validator {
    private static final Pattern PATTERN =
        Pattern.compile("^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\/(?:1[01][0-9]|12[0-8]|[0-9]{1,2})$|^::(?:[fF]{4}(?::0{1,4})?:)?(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})(?:\\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]{1,2})){3}\\/(?:1[01][0-9]|12[0-8]|[0-9]{1,2})$|^(?:[0-9a-fA-F]{0,4}:){1,7}(?::[0-9a-fA-F]{0,4}){0,7}\\/(?:1[01][0-9]|12[0-8]|[0-9]{1,2})$");

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

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

Test Cases

Matches (Valid)
Rejects (Invalid)
2001:db8::/322001:db8::/129
::1/1282001:db8::
fe80::/10::1
::/0192.168.0.0/24
2001:0db8:85a3:0000:0000:8a2e:0370:7334/64

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

IPv6 has multiple equivalent representations for the same address (:: compression, leading zero omission). Normalize to RFC 5952 canonical form before comparison or storage.

Technical Notes

IPv6 CIDR prefixes: /48 is common for ISP assignments, /64 for subnets (standard for SLAAC), /128 for single hosts. ::/0 is the IPv6 default route. fe80::/10 is link-local. ::1/128 is loopback.

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