Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match MAC address and also extract it's values

Tags:

python

regex

I'm trying to first check if a string confirms the format of a MAC address, and if it does I would like to extract all the byte values out of the string.

So far I wrote this, and it successfully matches if the format of a mac address is correct or not:

 mac_regx = re.compile(r'^([0-9A-F]{1,2})(\:[0-9A-F]{1,2}){5}$', re.IGNORECASE)

But when I use this regex to extract the byte values, I'm only getting the first and the last one:

(Pdb) print(mac_regx.findall('aa:bb:cc:dd:ee:ff'))
[('aa', ':ff')]

I know I could simply split by : and that would do the job. I was just hoping to be able to do both, the matching and value extraction, in only one step with one regex.

like image 206
replay Avatar asked Nov 01 '22 14:11

replay


1 Answers

If you want all the matches, you should avoid using {5}:

mac_regx = re.compile(r'^([0-9A-F]{1,2})\:([0-9A-F]{1,2})\:([0-9A-F]{1,2})\:([0-9A-F]{1,2})\:([0-9A-F]{1,2})\:([0-9A-F]{1,2})$', re.IGNORECASE)

or, shorter,

mac_regx = re.compile(r'^([0-9A-F]{1,2})' + '\:([0-9A-F]{1,2})'*5 + '$', re.IGNORECASE)

You could also make a list of 6 occurrences of a string '[0-9A-F]{1,2})' and join them with '\:'.

like image 183
Vedran Šego Avatar answered Nov 15 '22 05:11

Vedran Šego