Rexact
Cheatsheet

Regex IPv4 address in CIDR notation

The reference Stack Overflow question's author has a bug they notice themselves: their regex, meant to validate a CIDR prefix, also accepts "192.168.0.0/aaaa" - because the optional group is never followed by an end-of-string anchor. A 17-vote answer fixes the anchoring, but stays deliberately limited to /16 and /24 prefixes (the original ask); a comment proposes extending it to /16-/32, but misses the lower half of the range (/0 to /15). None of the attempts check that each octet stays under 256. Here's a pattern that covers the full /0-/32 range with genuinely bounded octets, compared against these 3 real attempts.

/^(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(?:\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}(?:/(?:3[0-2]|[12]?[0-9]))?$/
passes 20/20 cases

Comparison of existing patterns

Implementation

const re = new RegExp("^(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])(?:\\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])){3}(?:/(?:3[0-2]|[12]?[0-9]))?$", "");
re.test(input);

Limits

  • Valide seulement la forme : n'indique pas si l'adresse et le préfixe forment un bloc réseau correctement aligné (ex. « 192.168.0.5/24 » est syntaxiquement accepté même si .5 n'est pas une adresse réseau ronde pour ce préfixe).
  • N'accepte que la notation avec préfixe numérique (« /24 ») : le masque de sous-réseau à l'ancienne écriture décimale pointée (« 255.255.255.0 ») suit une syntaxe entièrement différente, non couverte ici.
  • Ne distingue pas les adresses réservées (privées RFC 1918, loopback, multicast) : la forme seule ne dit rien sur la routabilité ou l'usage réel de l'adresse.
  • Ne couvre pas IPv6 ni sa propre notation CIDR (« /64 », préfixes jusqu'à 128) : un motif séparé est nécessaire pour ce protocole.

Related pages