Skip to content
Related Articles

Related Articles

How to validate Hexadecimal Color Code using Regular Expression
  • Last Updated : 04 Feb, 2021
GeeksforGeeks - Summer Carnival Banner

Given string str, the task is to check whether the string is valid hexadecimal colour code or not by using Regular Expression.

The valid hexadecimal color code must satisfy the following conditions. 
 

  1. It should start from ‘#’ symbol.
  2. It should be followed by the letters from a-f, A-F and/or digits from 0-9.
  3. The length of the hexadecimal color code should be either 6 or 3, excluding ‘#’ symbol.

For example: #abc, #ABC, #000, #FFF, #000000, #FF0000, #00FF00, #0000FF, #FFFFFF are all valid Hexadecimal color codes.
Examples: 

Input: str = “#1AFFa1”; 
Output: true 
Explanation: 
The given string satisfies all the above mentioned conditions.
Input: str = “#F00”; 
Output: true 
Explanation: 
The given string satisfies all the above mentioned conditions.
Input: str = “123456”; 
Output: false 
Explanation: 
The given string doesn’t start with a ‘#’ symbol, therefore it is not a valid hexadecimal color code.
Input: str = “#123abce”; 
Output: false 
Explanation: 
The given string has length 7, the valid hexadecimal color code length should be either 6 or 3. Therefore it is not a valid hexadecimal color code.
Input: str = “#afafah”; 
Output: false 
Explanation: 
The given string contains ‘h’, the valid hexadecimal color code should be followed by the letter from a-f, A-F. Therefore it is not a valid hexadecimal color code. 

Approach: This problem can be solved by using Regular Expression. 



  • Get the string.
  • Create a regular expression to check valid hexadecimal color code as mentioned below:
regex = "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$";
  • Where: 
    • ^ represents the starting of the string.
    • # represents the hexadecimal color code must start with a ‘#’ symbol.
    • ( represents the start of the group.
    • [A-Fa-f0-9]{6} represents the letter from a-f, A-F, or digit from 0-9 with a length of 6.
    • | represents the or.
    • [A-Fa-f0-9]{3} represents the letter from a-f, A-F, or digit from 0-9 with a length of 3.
    • ) represents the end of the group.
    • $ represents the ending of the string.
  • Match the given string with the regex, in Java, this can be done by using Pattern.matcher().
  • Return true if the string matches with the given regex, else return false.

Below is the implementation of the above approach:

C++




// C++ program to validate the
// hexadecimal color code using Regular Expression
#include <iostream>
#include <regex>
using namespace std;
 
// Function to validate the hexadecimal color code.
bool isValidHexaCode(string str)
{
 
  // Regex to check valid hexadecimal color code.
  const regex pattern("^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$");
 
  // If the hexadecimal color code
  // is empty return false
  if (str.empty())
  {
     return false;
  }
 
  // Return true if the hexadecimal color code
  // matched the ReGex
  if(regex_match(str, pattern))
  {
    return true;
  }
  else
  {
    return false;
  }
}
 
// Driver Code
int main()
{
   
  // Test Case 1:
  string str1 = "#1AFFa1";
  cout << str1 + ": " << isValidHexaCode(str1) << endl;
 
  // Test Case 2:
  string str2 = "#F00";
  cout << str2 + ": " <<  isValidHexaCode(str2) << endl;
 
  // Test Case 3:
  string str3 = "123456";
  cout << str3 + ": " <<  isValidHexaCode(str3) << endl;
 
  // Test Case 4:
  string str4 = "#123abce";
  cout << str4 + ": " <<  isValidHexaCode(str4) << endl;
 
  // Test Case 5:
  string str5 = "#afafah";
  cout << str5 + ": " <<  isValidHexaCode(str5) << endl;
 
  return 0;
}
 
// This code is contributed by yuvraj_chandra

Java




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

Python3




# Python3 program to validate
# hexadecimal colour code using
# Regular Expression
import re
 
# Function to validate
# hexadecimal color code .
def isValidHexaCode(str):
 
    # Regex to check valid
    # hexadecimal color code.
    regex = "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$"
 
    # Compile the ReGex
    p = re.compile(regex)
 
    # If the string is empty
    # return false
    if(str == None):
        return False
 
    # Return if the string
    # matched the ReGex
    if(re.search(p, str)):
        return True
    else:
        return False
 
# Driver Code.
 
# Test Case 1:
str1 = "#1AFFa1"
print(str1, ":", isValidHexaCode(str1))
 
# Test Case 2:
str2 = "#F00"
print(str2, ":", isValidHexaCode(str2))
 
# Test Case 3:
str3 = "123456"
print(str3, ":", isValidHexaCode(str3))
 
# Test Case 4:
str4 = "#123abce"
print(str4, ":", isValidHexaCode(str4))
 
# Test Case 5:
str5 = "#afafah"
print(str5, ":", isValidHexaCode(str5))
 
# This code is contributed by avanitrachhadiya2155
Output: 
#1AFFa1: true
#F00: true
123456: false
#123abce: false
#afafah: false

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :