How to validate Hexadecimal Color Code using Regular Expression | Java program to validate hexadecimal colour code using Regular Expression ; Function to validate hexadecimal color code . ; Regex to check valid hexadecimal color code . ; Compile the ReGex ; If the string is empty return false ; Pattern class contains matcher ( ) method to find matching between given string and regular expression . ; Return if the string matched the ReGex ; Driver Code . ; Test Case 1 : ; Test Case 2 : ; Test Case 3 : ; Test Case 4 : ; Test Case 5 :
import java . util . regex . * ; class GFG { public static boolean isValidHexaCode ( String str ) { String regex = " ^ # ( [ A - Fa - f0-9 ] { 6 } ▁ [ A - Fa - f0-9 ] { 3 } ) $ " ; Pattern p = Pattern . compile ( regex ) ; if ( str == null ) { return false ; } Matcher m = p . matcher ( str ) ; return m . matches ( ) ; } public static void main ( String args [ ] ) { String str1 = " # 1AFFa1" ; System . out . println ( str1 + " : ▁ " + isValidHexaCode ( str1 ) ) ; String str2 = " # F00" ; System . out . println ( str2 + " : ▁ " + isValidHexaCode ( str2 ) ) ; String str3 = "123456" ; System . out . println ( str3 + " : ▁ " + isValidHexaCode ( str3 ) ) ; String str4 = " # 123abce " ; System . out . println ( str4 + " : ▁ " + isValidHexaCode ( str4 ) ) ; String str5 = " # afafah " ; System . out . println ( str5 + " : ▁ " + isValidHexaCode ( str5 ) ) ; } }