Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Pattern Searching
  • Tutorial on Pattern Searching
  • Naive Pattern Searching
  • Rabin Karp
  • KMP Algorithm
  • Z Algorithm
  • Trie for Pattern Seaching
  • Manacher Algorithm
  • Suffix Tree
  • Ukkonen's Suffix Tree Construction
  • Boyer Moore
  • Aho-Corasick Algorithm
  • Wildcard Pattern Matching
Open In App
Next Article:
Check if a given string is a valid Hexadecimal Color Code or not
Next article icon

Check if a given string is a valid Hexadecimal Color Code or not

Last Updated : 21 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string str, the task is to check whether the given string is an HTML Hex Color Code or not. Print Yes if it is, otherwise print No.

Examples: 

Input: str = “#1AFFa1”
Output: Yes

Input: str = “#F00”
Output: Yes

Input: str = �”
Output: No

 

Approach:  An HTML Hex Color Code follows the below-mentioned set of rules: 

  1. It starts with the ‘#’ symbol.
  2. Then it is 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.
  4. For example: #abc, #ABC, #000, #FFF, #000000, #FF0000, #00FF00, #0000FF, #FFFFFF are all valid Hexadecimal color codes.

Now, to solve the above problem follow the below steps:

  1. Check the string str for the following conditions:
    • If the first character is not #, return false.
    • If the length is not 3 or 6. If not, return false.
    • Now, check for all characters other than the first character that are 0-9, A-F or a-f.
  2. If all the conditions mentioned above are satisfied, then return true.
  3. Print answer according to the above observation.

Below is the implementation of the above approach:

CPP
// C++ program for the above approach  #include <iostream> using namespace std;  // Function to validate  // the HTML hexadecimal color code. bool isValidHexaCode(string str) {     if (str[0] != '#')         return false;      if (!(str.length() == 4 or str.length() == 7))         return false;      for (int i = 1; i < str.length(); i++)         if (!((str[i] >= '0' && str[i] <= 9)               || (str[i] >= 'a' && str[i] <= 'f')               || (str[i] >= 'A' || str[i] <= 'F')))             return false;      return true; }  // Driver Code int main() {     string str = "#1AFFa1";      if (isValidHexaCode(str)) {         cout << "Yes" << endl;     }     else {         cout << "No" << endl;     }     return 0; } 
Java
// Java program for the above approach import java.util.*; class GFG{      // Function to validate      // the HTML hexadecimal color code.     static boolean isValidHexaCode(String str)     {         if (str.charAt(0) != '#')             return false;          if (!(str.length() == 4 || str.length() == 7))             return false;          for (int i = 1; i < str.length(); i++)             if (!((str.charAt(i) >= '0' && str.charAt(i) <= 9)                 || (str.charAt(i) >= 'a' && str.charAt(i) <= 'f')                 || (str.charAt(i) >= 'A' || str.charAt(i) <= 'F')))                 return false;          return true;     }          // Driver code     public static void main(String args[])     {         String str = "#1AFFa1";          if (isValidHexaCode(str)) {             System.out.println("Yes");         }         else {             System.out.println("No");         }     } }  // This code is contributed by Samim Hossain Mondal. 
Python3
# python program for the above approach  # Function to validate # the HTML hexadecimal color code. def isValidHexaCode(str):      if (str[0] != '#'):         return False      if (not(len(str) == 4 or len(str) == 7)):         return False      for i in range(1, len(str)):         if (not((str[i] >= '0' and str[i] <= '9') or (str[i] >= 'a' and str[i] <= 'f') or (str[i] >= 'A' or str[i] <= 'F'))):             return False      return True   # Driver Code if __name__ == "__main__":      str = "#1AFFa1"      if (isValidHexaCode(str)):         print("Yes")      else:         print("No")      # This code is contributed by rakeshsahni 
C#
// C# program for the above approach using System; class GFG{      // Function to validate      // the HTML hexadecimal color code.     static bool isValidHexaCode(string str)     {         if (str[0] != '#')             return false;          if (!(str.Length == 4 || str.Length == 7))             return false;          for (int i = 1; i < str.Length; i++)             if (!((str[i] >= '0' && str[i] <= 9)                 || (str[i] >= 'a' && str[i] <= 'f')                 || (str[i] >= 'A' || str[i] <= 'F')))                 return false;          return true;     }          // Driver code     public static void Main()     {         string str = "#1AFFa1";          if (isValidHexaCode(str)) {             Console.Write("Yes");         }         else {             Console.Write("No");         }     } } // This code is contributed by Samim Hossain Mondal. 
JavaScript
 <script>         // JavaScript Program to implement         // the above approach          // Function to validate          // the HTML hexadecimal color code.         function isValidHexaCode(str) {             if (str[0] != '#')                 return false;              if (!(str.length == 4 || str.length == 7))                 return false;              for (let i = 1; i < str.length; i++)                 if (!((str[i].charCodeAt(0) <= '0'.charCodeAt(0) && str[i].charCodeAt(0) <= 9)                     || (str[i].charCodeAt(0) >= 'a'.charCodeAt(0) && str[i].charCodeAt(0) <= 'f'.charCodeAt(0))                     || (str[i].charCodeAt(0) >= 'A'.charCodeAt(0) || str[i].charCodeAt(0) <= 'F'.charCodeAt(0))))                     return false;              return true;         }          // Driver Code         let str = "#1AFFa1";          if (isValidHexaCode(str)) {             document.write("Yes" + '<br>');         }         else {             document.write("No" + '<br>');         }      // This code is contributed by Potta Lokesh     </script> 

Output
Yes

Time Complexity: O(N)
Auxiliary Space: O(1)

Approach 2: Regex Expression:

In this approach, we have used regex library to define a regular expression pattern to match the HTML hexadecimal color code. The regular expression pattern ^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$ matches the string that starts with # and followed by either 6 hexadecimal digits or 3 hexadecimal digits. The regex_match function checks if the given string matches the regular expression pattern or not, and returns true if it matches, else false.

Here is the code given below:

C++
#include <iostream> #include <regex> using namespace std;  // Function to validate  // the HTML hexadecimal color code using regex. bool isValidHexaCode(string str) {     regex hexaCode("^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$");     return regex_match(str, hexaCode); }  // Driver Code int main() {     string str = "#1AFFa1";      if (isValidHexaCode(str)) {         cout << "Yes" << endl;     }     else {         cout << "No" << endl;     }     return 0; } 
Java
import java.util.regex.Pattern; import java.util.regex.Matcher;  public class GFG {      // Function to check if a given string is a valid hexadecimal color code     public static boolean isValidHexaCode(String input) {         // Define the regular expression pattern for a valid hexadecimal color code         // It matches either a 6-character or 3-character code, preceded by a #         Pattern hexaPattern = Pattern.compile("^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$");                  // Create a Matcher object to match the input against the pattern         Matcher matcher = hexaPattern.matcher(input);                  // Return true if the input matches the pattern, otherwise false         return matcher.matches();     }      public static void main(String[] args) {         String input = "#1AFFa1";          if (isValidHexaCode(input)) {             System.out.println("Yes");         } else {             System.out.println("No");         }     } } 
Python3
import re  def is_valid_hexa_code(string):     hexa_code = re.compile(r'^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$')     return bool(re.match(hexa_code, string))  if __name__ == "__main__":     string = "#1AFFa1"      if is_valid_hexa_code(string):         print("Yes")     else:         print("No") 
C#
using System; using System.Text.RegularExpressions;  class GFG {     // Function to validate the HTML hexadecimal color code using regex.     static bool IsValidHexaCode(string str)     {         // Regular expression to match a valid hexadecimal color code.         // The pattern "^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$" checks for:         // ^        - Start of the string         // #        - The string must start with a hash character (#)         // (        - Start of the first group         // [a-fA-F0-9]{6} - Matches exactly six characters which can be any of a-f, A-F, or 0-9         // |        - OR         // [a-fA-F0-9]{3} - Matches exactly three characters which can be any of a-f, A-F, or 0-9         // )        - End of the first group         // $        - End of the string         Regex hexaCode = new Regex(@"^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$");          // Check if the input string matches the regex pattern.         return hexaCode.IsMatch(str);     }      static void Main()     {         string str = "#1AFFa1";          if (IsValidHexaCode(str))         {             Console.WriteLine("Yes");         }         else         {             Console.WriteLine("No");         }     } } 
JavaScript
function isValidHexaCode(input) {     // Define the regular expression pattern for a valid hexadecimal color code     // It matches either a 6-character or 3-character code, preceded by a #     var hexaPattern = /^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/;      // Test the input against the pattern using the test() method     return hexaPattern.test(input); }  var input = "#1AFFa1";  if (isValidHexaCode(input)) {     console.log("Yes"); } else {     console.log("No"); } 

Output
Yes


Time Complexity: O(N)
Auxiliary Space: O(1)


Next Article
Check if a given string is a valid Hexadecimal Color Code or not

C

code_r
Improve
Article Tags :
  • Misc
  • Strings
  • Pattern Searching
  • Mathematical
  • DSA
Practice Tags :
  • Mathematical
  • Misc
  • Pattern Searching
  • Strings

Similar Reads

    Check if the given RGB color code is valid or not
    Given three numbers R, G and B as the color code for Red, Green and Blue respectively as in the form of RGB color code. The task is to know whether the given color code is valid or not. RGB Format: The RGB(Red, Green, Blue) format is used to define the color of an HTML element by specifying the R, G
    10 min read
    Check if a HexaDecimal number is Even or Odd
    Given a HexaDecimal number, check whether it is even or odd.Examples: Input: N = ABC7787CC87AA Output: Even Input: N = 9322DEFCD Output: Odd Naive Approach: Convert the number from Hexadecimal base to Decimal base.Then check if the number is even or odd, which can be easily checked by dividing by 2.
    4 min read
    How to validate Hexadecimal Color Code using Regular Expression
    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. It should start from '#' symbol.It should be followed by the letters from a-f, A-F and/or digits from
    6 min read
    Check if given Binary string follows then given condition or not
    Given binary string str, the task is to check whether the given string follows the below condition or not: String starts with a '1'.Each '1' is followed by empty string(""), '1', or "00".Each "00" is followed by empty string(""), '1'. If the given string follows the above criteria then print "Valid
    10 min read
    Check if a binary string contains consecutive same or not
    Given a binary string str consisting of characters '0' and '1'. The task is to find whether the string is valid or not. A string is valid only if the characters are alternating i.e. no two consecutive characters are the same. Examples: Input: str[] = "010101" Output: Valid Input: str[] = "010010" Ou
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences