REGEXVAULTv2.0
Web & Network/IPv4
Verified Safe

IPv4 with CIDR Notation Regex for Go

/^(?:(?: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

Need to validate IPv4 addresses with CIDR notation in your Go application? This carefully crafted regular expression handles the complex task of matching and validating both the IP address and the prefix length. Whether you're building a network configuration tool or securing an API, this regex provides a reliable way to ensure the format is correct. Integrate it directly into your Go code for robust input validation.

Go Implementation

Go
// IPv4 with CIDR Notation
// ReDoS-safe | RegexVault — Web & Network > IPv4

package validation

import "regexp"

var ipv4WithCidrNotationRe = regexp.MustCompile(`^(?:(?: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])$`)

func ValidateIpv4WithCidrNotation(s string) bool {
    return ipv4WithCidrNotationRe.MatchString(s)
}

// Example
// fmt.Println(ValidateIpv4WithCidrNotation("192.168.0.0/24")) // true

Test Cases

Matches (Valid)
Rejects (Invalid)
192.168.0.0/24192.168.1.1/33
10.0.0.0/8256.0.0.0/24
0.0.0.0/0192.168.1/24
255.255.255.255/32192.168.0.0/
172.16.0.0/12192.168.0.0

When to use this pattern

While Go's RE2 engine protects against ReDoS vulnerabilities, this specific pattern provides extra assurance. The regex has been manually audited and tested to guarantee correctness. This is critical in network applications, such as a Kubernetes admission controller or a service mesh sidecar proxy. Deploying with confidence means avoiding unexpected behavior. This pattern is production-ready for validating user input or network configurations.

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