IPv4 regexp improvements
I saw quite nice post and answer on StackOverflow about an IPv4 address regexp. This made me improve a little address and prefix regexps.
Single octet, lazy:
(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])
(47 characters)
Single octet, smarter:
(25[0-5]|(2[0-4]|1\d|[1-9]|)\d)
(31 characters)
The same technique used with prefix regexp from:
([0-9]|[1-2][0-9]|3[0-2])
(25 characters) to:
(3[0-2]|[1-2]?\d)
(17 characters)
Word boundary assertion trick is used to simplify(?) dot handling:
^([octet]\.){3}[octet]$
replaced with
^([octet]\.?\b){4}$
Finally we have:
^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}$
for an IPv4 address and
^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)\.?\b){4}(\/(3[0-2]|[1-2]?\d))?$
for an IPv4 address or prefix (CIDR notation).
Regexps tested with https://regex101.com/
Note: grep doesn't support \d, so grep versions are:
^((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])\.?\b){4}$
^((25[0-5]|(2[0-4]|1[0-9]|[1-9]|)[0-9])\.?\b){4}(\/(3[0-2]|[1-2]?[0-9]))?$