Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expression for ipaddress and mac address

can anyone suggest me the regular expression for ip address and mac address ?

i am using python & django

for example , http://[ipaddress]/SaveData/127.0.0.1/00-0C-F1-56-98-AD/

for mac address i tried following but didn't work

([0-9A-F]{2}[:-]){5}([0-9A-F]{2})

^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$
like image 938
Hunt Avatar asked Dec 03 '22 09:12

Hunt


2 Answers

import re
s = "http://[ipaddress]/SaveData/127.0.0.1/00-0C-F1-56-98-AD/"

re.search(r'([0-9A-F]{2}[:-]){5}([0-9A-F]{2})', s, re.I).group()
'00-0C-F1-56-98-AD'

re.search(r'((2[0-5]|1[0-9]|[0-9])?[0-9]\.){3}((2[0-5]|1[0-9]|[0-9])?[0-9])', s, re.I).group()
'127.0.0.1'

Place this snippet in your django routing definitions file - urls.py

url(r'^SaveData/(?P<ip>((2[0-5]|1[0-9]|[0-9])?[0-9]\.){3}((2[0-5]|1[0-9]|[0-9])?[0-9]))/(?P<mac>([0-9A-F]{2}[:-]){5}([0-9A-F]{2}))', SaveDataHandler.as_view()),
like image 116
Michal Chruszcz Avatar answered Dec 21 '22 05:12

Michal Chruszcz


Your regular expression only contains two capturing groups (parentheses), so it isn't storing the entire address (the first group gets "overwritten"). Try these:

# store each octet into its own group
r"([\dA-F]{2})[-:]([\dA-F]{2})[-:]([\dA-F]{2})[-:]([\dA-F]{2})[-:]([\dA-F]{2})[-:]([\dA-F]{2})"
# store entire MAC address into a single group
r"([\dA-F]{2}(?:[-:][\dA-F]{2}){5})"

IP addresses get trickier because the ranges are binary but the representation is decimal.

# store each octet into its own group
r"(\d|[1-9]\d|1\d\d|2(?:[0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2(?:[0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2(?:[0-4]\d|5[0-5]))\.(\d|[1-9]\d|1\d\d|2(?:[0-4]\d|5[0-5]))"
# store entire IP address into a single group
r"((?:\d|[1-9]\d|1\d\d|2(?:[0-4]\d|5[0-5]))(?:\.(?:\d|[1-9]\d|1\d\d|2(?:[0-4]\d|5[0-5]))){3})"
like image 42
Ben Blank Avatar answered Dec 21 '22 05:12

Ben Blank