Regular Expressions 101

Community Patterns

IPv4 address with optional CIDR suffix

1

Regular Expression
ECMAScript (JavaScript)

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

Description

Matches any valid IPv4 address with, optionally, a CIDR suffix.

0.0.0.0 to 255.255.255.255 and 1.1.1.1/0 to 1.1.1.1/32.

Use the following regex if you don't want to allow the CIDR suffix.

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

(removed (?:\/(?:[12]?[0-9]|3[0-2]))? from the end)

Submitted by MAZ01001 - 2 months ago