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.
.
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}$
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}$
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
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.
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.
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