IPv4 with CIDR Notation 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])\/(?:3[0-2]|[12][0-9]|[0-9])$/What this pattern does
Validating IPv4 addresses with CIDR notation in Java applications is made easy with this robust regular expression. This pattern accurately parses addresses like 192.168.1.0/24, ensuring both address correctness and the validity of the prefix length. Use this regex to confidently validate network configurations within your Java code, such as when parsing input from a configuration file or from user-supplied data in a web application.
Java Implementation
// IPv4 with CIDR Notation
// ReDoS-safe | RegexVault — Web & Network > IPv4
import java.util.regex.Pattern;
public class Ipv4WithCidrNotationValidator {
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])\\/(?:3[0-2]|[12][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("192.168.0.0/24")); // true
}
}Test Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
192.168.0.0/24 | 192.168.1.1/33 |
10.0.0.0/8 | 256.0.0.0/24 |
0.0.0.0/0 | 192.168.1/24 |
255.255.255.255/32 | 192.168.0.0/ |
172.16.0.0/12 | 192.168.0.0 |
When to use this pattern
In Java, a ReDoS attack can cripple an application by consuming excessive CPU resources during regex evaluation, especially when processing untrusted input. This specific pattern from RegexVault is designed to mitigate this risk, guarding against pathological backtracking scenarios that could arise from crafted input. Deploy this pattern with confidence in environments such as API gateways or network monitoring tools, knowing that your Java application is protected from this class of denial-of-service vulnerability.
Common Pitfalls
Using [0-9]{1,2} for the prefix allows /99. Always use the bounded alternation.
Technical Notes
Prefix length alternatives: 3[0-2] covers 30–32, [12][0-9] covers 10–29, [0-9] covers 0–9. Combined this gives 0–32 exactly.
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