I'm facing the following problem : I need two regexp to validate if an IPV4 and IPV4-cidr is valid.
const iPv4 =
/^(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])(?<!172.(16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31))(?<!127)(?<!^10)(?<!^0).(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])(?<!192.168)(?<!172.(16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)).(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5]).(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])(?<!.255$)$/;
And
const iPv4Cidr =
/^(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])(?<!172.(16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31))(?<!127)(?<!^10)(?<!^0).(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])(?<!192.168)(?<!172.(16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)).(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5]).(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])(?<!.255$)[/](24|25|26|27|28|29|30|31|32)$/;
My problem is that lookbehind is not supported by Safari , Is there a way to transform those regexp without using lookbehind ?
Thx
I tried different librairies such as is-ip / ip-regex and is-cidr / cidr-regex but none of them fits.
It validates local IPs such as
const localIPs = [
'172.16.0.9',
'172.16.4.1',
'172.17.1.1',
'127.0.0.2',
'10.0.1.5',
'10.0.0.1',
'10.155.155.155',
'10.255.255.254',
'172.16.0.4',
'172.16.0.1',
'172.17.1.1',
'172.31.254.254',
'192.168.1.2',
'192.168.254.0',
]
or broadcasted IPs such as
const broadcastIPs = ['60.123.247.255', '196.168.255.255', '10.255.255.255', '192.168.255.255'];
Note that in your regex, the first (?<!172.(16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31))
lookbehind is redundant as it does not do anything real.
To fix the issue, the lookebehinds need to be converted to lookaheads, and \b
word boundaries can be used at the end of their patterns to so as to ensure exact number matching.
You can use
^(?!127)(?!10\b)(?!0\b)(?!192\.168\b)(?!172\.(16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31)\b)(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.(?!255)(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])$
See the regex demo.