Python Forum
re: normalize of mac address
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
re: normalize of mac address
#1
Colleagues, tell me, please, the answer to my question.

I have a variable that contains the mac address.
Here is a regular expression describing it -
r'^\w{1,2}:\w{1,2}:\w{1,2}:\w{1,2}:\w{1,2}:\w{1,2}$'
Now I want to one-sign bytes of address be supplemented by zero.

For this, I wrote this code:
mac = re.sub(r'^(\w):',r'0\1:',mac)
mac = re.sub(r':(\w):',r':0\1:',mac)
mac = re.sub(r':(\w)$',r':0\1',mac)
Unfortunately, the second line of code does not replace all the substrings matching the regular expression.

If I write to a variable mac value
Quote:'1:2:3:4:5:6'
, then after code execution, its value
Quote:01:02:3:04:5:06

Please tell me what am I doing wrong?

Ogogon.
Reply
#2
Can try this.
>>> import re
>>> 
>>> mac = '1:2:3:4:5:6'
>>> re.sub(r'(\d):?', r'0\1:', mac).strip(':')
'01:02:03:04:05:06'
Reply
#3
(Dec-02-2019, 12:47 AM)snippsat Wrote: Can try this.
I think this is not a good idea.
Firstly, all bytes in the mac address are specified in hexadecimal encoding, and therefore in the regular expression need to use the '\w' macro, but not '\d'.
Secondly, your option, unfortunately, does not take into account the fact that some bytes can already be two-digit.

If I enter this mac-address
Quote:01:2:03:04:ff:6
I will get an answer
Quote:00:01:02:00:03:00:04:0f:0f:06
.
Instead
Quote:01:02:03:04:ff:06

Ogogon.
Reply
#4
How about this?
def normalize_mac(mac):
    parts = [int(x, 16) for x in mac.split(':')]
    return ':'.join(f"{part:02x}" for part in parts)
I would guess there's a more direct way than converting to an int first, but I think this works for your requirements. I'll leave optimizing it as an exercise to the reader :)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020