1

I want to match IP range using a Python regex.

For Ex. the google bot IP range as follow

66.249.64.0 - 66.249.95.255

re.compile(r"66.249.\d{1,3}\.\d{1,3}$")

I can not figure out how to do this? I found this one done using Java.

3
  • Are you trying to locate an ip address within a larger text, or do you have a string which only contains the ip address? Commented Jul 16, 2013 at 9:09
  • @Joel Cornett : I have a text file with ip addresses, I want to filter some ip addresses from it Commented Jul 16, 2013 at 9:11
  • Side note: if you're doing a lot of work with network addresses, you may want to check into the netaddr package. Commented Jul 16, 2013 at 9:27

3 Answers 3

1

You can use this:

re.compile(r"66\.249\.(?:6[4-9]|[78]\d|9[0-5])\.\d{1,3}$")

if you are motivated you can replace \d{1,3} by :

(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)

Explanation:

A regex engine doesn't know what a numeric range is. The only way to describe a range is to write all the possibilities with alternations:

6[4-9]  |  [78][0-9]  |  9[0-5] 

6          can be followed by    4 to 9   --> 64 to 69
7 or 8     can be followed by    0 to 9   --> 70 to 89
9          can be followed by    0 to 5   --> 90 to 95 
Sign up to request clarification or add additional context in comments.

2 Comments

Excellant..:) Worked Well, Thanks a lot!
One more thing, Could you please explain this?
1

Use socket.inet_aton:

import socket
ip_min, ip_max = socket.inet_aton('66.249.64.0'), socket.inet_aton('66.249.95.255')

if ip_min <= socket.inet_aton('66.249.63.0') <= ip_max:
    #do stuff here

Comments

0

The last digit is:

[01]?\d{1,2}|2[0-4]\d|25[0-5]

The 3rd digit is:

6[4-9])|[78]\d|9[0-5]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.