How to validate Hexadecimal Color Code using Regular Expression | Python3 program to validate hexadecimal colour code using Regular Expression ; Function to validate hexadecimal color code . ; Compile the ReGex ; If the string is empty return false ; Return if the string matched the ReGex ; Test Case 1 : str1 = "1AFFa1" ; Test Case 2 : str2 = " F00" ; Test Case 3 : ; Test Case 4 : str4 = "123abce " ; Test Case 5 : str5 = " afafah "
import re NEW_LINE def isValidHexaCode ( str ) : NEW_LINE INDENT 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 print ( str1 , " : " , isValidHexaCode ( str1 ) ) NEW_LINE print ( str2 , " : " , isValidHexaCode ( str2 ) ) NEW_LINE str3 = "123456" NEW_LINE print ( str3 , " : " , isValidHexaCode ( str3 ) ) NEW_LINE print ( str4 , " : " , isValidHexaCode ( str4 ) ) NEW_LINE print ( str5 , " : " , isValidHexaCode ( str5 ) ) NEW_LINE