Skip to content

Instantly share code, notes, and snippets.

@rubinsaifi
Created November 28, 2017 06:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rubinsaifi/1650547aa33f305f1c983ba77ee5eec3 to your computer and use it in GitHub Desktop.
Save rubinsaifi/1650547aa33f305f1c983ba77ee5eec3 to your computer and use it in GitHub Desktop.
IPv4 Regex
# this is correction to https://stackoverflow.com/a/39136481
# Following is python
import re
ip_list = ['10.101.0.11','011.101.232.111', '01.01.01.01','000.000.000.000','00.00.00.00','0.0.0.0','011.022.022.011']
regex = r'^(25[0-5]|2[0-4][0-9]|[1-2]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[1-2]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[1-2]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[1-2]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$'
for i in ip_list:
resp = re.match(regex, i)
print ('match', i) if resp else print("not match", i)
output:
match 10.101.0.11
not match 011.101.232.111
not match 01.01.01.01
not match 000.000.000.000
not match 00.00.00.00
not match 0.0.0.0
@rubinsaifi
Copy link
Author

You can also checkout: https://gist.github.com/mnordhoff/2213179 which has support for IPv6

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment