0

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

d82k
  • 379
  • 7
  • 17
  • 3
    Does this answer your question? [Validating IPv4 addresses with regexp](https://stackoverflow.com/questions/5284147/validating-ipv4-addresses-with-regexp) – Stephane Janicaud Mar 31 '20 at 21:35

1 Answers1

1

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

blhsing
  • 91,368
  • 6
  • 71
  • 106