RegEx IP range class A network

Viewed 85

I am trying to filter IP Range, which partially works as it also includes a higher range.

I need only the range from 10.0.0.1 until 10.20.0.254.

The problem is that it also matches the network 10.x.120.x.

Here is the syntax I used:

egrep '10.([0-9]{1,3}).([0-1]|[0-9]|20).([0-9]{1,3})'

Example:

echo '10.2.120.0' | egrep '10.([0-9]{1,3}).([0-1]|[0-9]|20).([0-9]{1,3})'

It also prints undesirable IPs. I would like to limit it to 10.x.20.x.

1 Answers

With your shown samples, could you please try following.

10\.(?:[0-9]|[0-1][0-9]?|20)\.0\.(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[2-9][0-9]|1[1-9]|[1-9])

Online demo for above regex

With GNU grep it would be:

grep -oP '10\.(?:[0-9]|[0-1][0-9]?|20)\.0\.(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[2-9][0-9]|1[1-9]|[1-9])' Input_file

Explanation:

10\.(?:[0-9]|[0-1][0-9]?|20)\.0\.                         
##Matching 10 dot and range from 0 to 20 here, followed by 0. here.
(?:25[0-4]|2[0-4][0-9]|1[0-9][0-9]|[2-9][0-9]|1[1-9]|[1-9])  
##Matching from 1 to 254 range here in a non-capturing group.
Related