Reputation: 379
From a similar string below I would like to extract only the valid IPv4 addresses
233.444.444.222 , 127.0.0.1 , 127.0.0.0.1 , 192.168.1.1 , 812.1.1.1.1
where I have some valid ip addresses and some random numbers separated by "." Using the below:
\b(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\b
I extract also 127.0.0.0 and 1.1.1.1 which are not good. Any suggestion please?
KR dk
Upvotes: 0
Views: 95
Reputation: 106465
You can use negative lookarounds to avoid matching an IP-address led or trailed by a dot:
(?<!\.)\b(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\b(?!\.)
Demo: https://regex101.com/r/6yHTnY/1
Upvotes: 1