-
-
Save andreztz/791d019d093e53bc04b25a925fac24b5 to your computer and use it in GitHub Desktop.
Validate a MAC address using REGEX in Python 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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