I'm reading in MAC addresses on my LAN using the arp -a
command and parsing the output. On OS X, some MAC addresses are returned with hex values lacking leading zeros. I've figured out how to insert the leading zeros using regex:
>>> mac = '8:AA:C:3:ED:E'
>>> mac = re.sub('^(?P<hex>.)(?=\:)','0\g<hex>',mac)
>>> mac = re.sub('(?<=\:)(?P<hex>.)(?=\:)','0\g<hex>',mac)
>>> mac = re.sub('(?<=\:)(?P<hex>.)$','0\g<hex>',mac)
>>> print mac
08:AA:0C:03:ED:0E
This works, but I'm sure there's a way to perform a replacement in a single line for an arbitrary MAC address, where any hex value can potentially lack a leading zero...I just can't figure it out.