REGEXVAULTv2.0
Security/Network Security
Verified Safe

CIDR Notation (IPv6) Regex for Go

/^(?:[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 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 (IPv6)
// ReDoS-safe | RegexVault — Security > Network Security

package validation

import "regexp"

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

func ValidateCidrNotationIpv6(s string) bool {
    return cidrNotationIpv6Re.MatchString(s)
}

// Example
// fmt.Println(ValidateCidrNotationIpv6("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 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

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