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

I want regex to find IP address which not starts with 172.0.0.0.

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

Asked By: Sarvani Annamraju
||

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:

^172\.\d{1,3}\.\d{1,3}.\d{1,3}$

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.

^(?!172)\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}$

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 $

\b(?!172)\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}\b

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 10.14.242.211 established.

Answered By: Shadow

Answer #2:

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

\b((?!172)\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b

See a demo on regex101.com.

Answered By: Jan

Answer #3:

Try this:

^172\.(?:\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){2}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b|null)$

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 https://regex101.com/r/lA1gA4/1

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