Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
572 views
in Technique[技术] by (71.8m points)

python - How do I validate the format of a MAC address?

What's the best way to validate that an MAC address entered by the user?

The format is HH:HH:HH:HH:HH:HH, where each H is a hexadecimal character.

For instance, 00:29:15:80:4E:4A is valid while 00:29:804E4A is invalid.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you mean just the syntax then this regexp should work for you

import re
...
if re.match("[0-9a-f]{2}([-:]?)[0-9a-f]{2}(\1[0-9a-f]{2}){4}$", x.lower()):
    ...

it accepts 12 hex digits with either : or - or nothing as separators between pairs (but the separator must be uniform... either all separators are : or are all - or there is no separator).

This is the explanation:

  • [0-9a-f] means an hexadecimal digit
  • {2} means that we want two of them
  • [-:]? means either a dash or a colon but optional. Note that the dash as first char doesn't mean a range but only means itself. This subexpression is enclosed in parenthesis so it can be reused later as a back reference.
  • [0-9a-f]{2} is another pair of hexadecimal digits
  • \1 this means that we want to match the same expression that we matched before as separator. This is what guarantees uniformity. Note that the regexp syntax is 1 but I'm using a regular string so backslash must be escaped by doubling it.
  • [0-9a-f]{2} another pair of hex digits
  • {4} the previous parenthesized block must be repeated exactly 4 times, giving a total of 6 pairs of digits: <pair> [<sep>] <pair> ( <same-sep> <pair> ) * 4
  • $ The string must end right after them

Note that in Python re.match only checks starting at the start of the string and therefore a ^ at the beginning is not needed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...