Skip to content

Instantly share code, notes, and snippets.

@EONRaider
Last active August 19, 2024 23:43
Show Gist options
  • Save EONRaider/c34f6799b9cf2259e90fce54a39d693c to your computer and use it in GitHub Desktop.
Save EONRaider/c34f6799b9cf2259e90fce54a39d693c to your computer and use it in GitHub Desktop.
Validate a MAC address using REGEX in Python 3
#!/usr/bin/env python3
# https://gist.github.com/EONRaider/c34f6799b9cf2259e90fce54a39d693c
__author__ = 'EONRaider, keybase.io/eonraider'
import re
def validate_mac(mac_address: str) -> bool:
is_valid_mac = re.match(r'([0-9A-F]{2}[:]){5}[0-9A-F]{2}|'
r'([0-9A-F]{2}[-]){5}[0-9A-F]{2}',
string=mac_address,
flags=re.IGNORECASE)
try:
return bool(is_valid_mac.group()) # True if match
except AttributeError:
return False
if __name__ == '__main__':
assert validate_mac('11:22:33:44:55:66') is True
assert validate_mac('AA:BB:CC:DD:EE:FF') is True
assert validate_mac('11:22:33:AA:BB:CC') is True
assert validate_mac('11-22-33-AA-BB-CC') is True
assert validate_mac('22:33:AA:BB-CC-DD') is False
assert validate_mac('22-33-AA:BB:CC') is False
assert validate_mac('22:33:HH:BB:CC') is False
assert validate_mac('22:33:AA:BB:CC') is False
assert validate_mac('') is False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment