Requires regex to intercept IP addresses, excluding loop

I want to find all ip addresses in a file. The problem is that I need to exclude the address 127.0.0.1. I am using grep in linux bash. Here is what I already have:

[0-9]+.\.[0-9]+\.[0-9]+\.[0-9]+ 
+4
source share
2 answers

This will do:

 ^(?!127\.0{1,3}\.0{1,3}\.0{0,2}1$)((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$ 

Test http://regexr.com/3g3ov

I changed the quantifiers to {1,3} .

(?!127\.0{1,3}\.0{1,3}\.0{0,2}1$) means that you should not have 127.0.0.1 (after all, with some 0 )

((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3} for the first three-digit groups with them . , (25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?) For the last group of digits.

And I attached the regex to the beginning of ^ and completes the $ line.

If you want to exclude all loopback checks (so 127.*.*.* )

 ^(?!127)((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$ 

Test http://regexr.com/3g3os

The two regular expressions are based on the regular expression http://www.regular-expressions.info/examples.html minus the parts about unbound groups.

Here I should check only that the first group of digits is not 127 ( (?!127) )

This regular expression is complete, and it won’t accept things like 256.256.256.256 , but it is only for IPv4.

+4
source

In fact, the entire subnet 127.0.0.0/8 is reserved for loopback (so 127.45.78.32 is also a loopback address). Therefore, to solve your question with a regular expression, you must first check that the input line does not match:

 ^127\. 

and then check if it matches the regular regular IP address.

+1
source

Source: https://habr.com/ru/post/1495328/


All Articles