Regex for find All ip address except IP address starts with 172

I want regex to find IP address which not starts with

I have written some regex ^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$ which finds all ip address.

Answer #1:

. in a regex is character that matches everything. To use it in this context, you must escape it.

Also to limit it to just ip addresses that start with 172, simply hardcode it into your regex like so:


Regular expression visualization

Debuggex Demo

You could then use this to filter out any matches already made.

Alternatively, if you're not starting with a list of ip addresses, you could use a negative look-ahead to grab them all straight away.


Regular expression visualization

Debuggex Demo

Be a little careful in that this may match more than ip addresses - for example 400.660.226.602 would be captured - even though real IP4 addresses do not contain numbers higher than 255. Perhaps this won't affect your use case - but it's something to remember.

As per the comments below, if you are searching for IP addresses anywhere in the document, rather than on their own line, use \b instead of ^ and $


Regular expression visualization

Debuggex Demo

This would match log formats for example, which contain an ip address within the message rather than on it's own line.

[10:01:22] Connection from established.

Answered By: Shadow

Answer #2:

Use a negative lookahead if you're looking for addresses in the wild:


See a demo on

Answered By: Jan

Answer #3:

Try this:


It not only check ip address start with 172 but it also check for valid ip - address i.e each value can not be more than 255

Live demo is here

Answered By: R.K.Saini
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

# More Articles