REGEXVAULTv2.0
Security/Network Security
Verified Safe

CIDR Notation (IPv4) Regex for Go

/^(?:(?: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 Go. 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 Go project — whether you're validating in a Gin handler, a gRPC service, or a command-line tool.

Go Implementation

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

package validation

import "regexp"

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

func ValidateCidrNotationIpv4(s string) bool {
    return cidrNotationIpv4Re.MatchString(s)
}

// Example
// fmt.Println(ValidateCidrNotationIpv4("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 Go developers because Go's RE2 engine is inherently safe from catastrophic backtracking, but this pattern has been additionally verified for correctness. 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