Regexp for extracting public IP address

bigdatamarkRecently I needed to make a regular expression for parsing the first public IPV4 address from a string of comma separated private and public IP addresses.

After spending an hour on it and failing, I thought about it over night and woke up with some more ideas of what to try.

I ended up using a word boundary as an anchor and a negative lookahead from the anchor to accomplish it.

Test string:

'10.56.39.225, 10.0.0.1, 192.168.0.1, 172.16.1.1, 172.32.1.1, 172.1.1.1,'

Regex:

\b(?!(10)|192\.168|172\.(2[0-9]|1[6-9]|3[0-2]))[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}

2 Replies to “Regexp for extracting public IP address”

  1. I found the last 3 octets to be a bit permissive – modified it in my case as it identified invalid octets (serial numbers, versions, etc.) in my data sets:

    \b(?!(10)|192\.168|172\.(2[0-9]|1[6-9]|3[0-2]))[0-9]{1,3}\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)

Leave a Reply

Your email address will not be published. Required fields are marked *