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.
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 '\:'
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With