How to validate MAC address using Regular Expression | Python3 program to validate MAC address using using regular expression ; Function to validate MAC address . ; Regex to check valid MAC address ; Compile the ReGex ; If the string is empty return false ; Return if the string matched the ReGex ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 :
import re NEW_LINE def isValidMACAddress ( str ) : NEW_LINE INDENT regex = ( " ^ ( [0-9A - Fa - f ] {2 } [ : - ] ) " + " { 5 } ( [0-9A - Fa - f ] {2 } ) | " + " ( [0-9a - fA - F ] {4 } \\ . " + " [ 0-9a - fA - F ] {4 } \\ . " + " [ 0-9a - fA - F ] {4 } ) $ " ) NEW_LINE p = re . compile ( regex ) NEW_LINE if ( str == None ) : NEW_LINE INDENT return False NEW_LINE DEDENT if ( re . search ( p , str ) ) : NEW_LINE INDENT return True NEW_LINE DEDENT else : NEW_LINE INDENT return False NEW_LINE DEDENT DEDENT str1 = "01-23-45-67-89 - AB " NEW_LINE print ( isValidMACAddress ( str1 ) ) NEW_LINE str2 = "01:23:45:67:89 : AB " NEW_LINE print ( isValidMACAddress ( str2 ) ) NEW_LINE str3 = "0123.4567.89AB " NEW_LINE print ( isValidMACAddress ( str3 ) ) NEW_LINE str4 = "01-23-45-67-89 - AH " NEW_LINE print ( isValidMACAddress ( str4 ) ) NEW_LINE str5 = "01-23-45-67 - AH " NEW_LINE print ( isValidMACAddress ( str5 ) ) NEW_LINE