How to validate Hexadecimal Color Code using Regular Expression
Last Updated :
26 Dec, 2022
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 0-9.
- 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
C#
// C# program to validate
// hexadecimal colour code using
// using regular expression
using System;
using System.Text.RegularExpressions;
class GFG
{
// Main Method
static void Main(string[] args)
{
// Input strings to Match
//hexadecimal colour code
string[] str={"#1AFFa1","#F00","123456","#123abce","#afafah"};
foreach(string s in str) {
Console.WriteLine( isValidHexaCode(s) ? "true" : "false");
}
Console.ReadKey(); }
// method containing the regex
public static bool isValidHexaCode(string str)
{
string strRegex = @"^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$";
Regex re = new Regex(strRegex);
if (re.IsMatch(str))
return (true);
else
return (false);
}
}
// This code is contributed by Rahul Chauhan
JavaScript
// Javascript program to validate
// Hexadecimal Color Code using Regular Expression
// Function to validate the
// hexadecimalColor_code
function isValidHexaCode(str) {
// Regex to check valid
// hexadecimalColor_code
let regex = new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/);
// if str
// is empty return false
if (str == null) {
return "false";
}
// Return true if the str
// matched the ReGex
if (regex.test(str) == true) {
return "true";
}
else {
return "false";
}
}
// Driver Code
// Test Case 1:
let str1 = "#1AFFa1";
console.log(isValidHexaCode(str1));
// Test Case 2:
let str2 = "#F00";
console.log(isValidHexaCode(str2));
// Test Case 3:
let str3 = "123456";
console.log(isValidHexaCode(str3));
// Test Case 4:
let str4 = "#123abce";
console.log(isValidHexaCode(str4));
// Test Case 5:
let str5 = "#afafah";
console.log(isValidHexaCode(str5));
// This code is contributed by Rahul Chauhan
Output: #1AFFa1: true
#F00: true
123456: false
#123abce: false
#afafah: false
Time Complexity: O(N) for each testcase, where N is the length of the given string.
Auxiliary Space: O(1)
Similar Reads
How to validate IFSC Code using Regular Expression
Given string str, the task is to check whether the given string is a valid IFSC (Indian Financial System) Code or not by using Regular Expression. The valid IFSC (Indian Financial System) Code must satisfy the following conditions: It should be 11 characters long.The first four characters should be
8 min read
How to validate pin code of India using Regular Expression
Given a string of positive number ranging from 0 to 9, the task is to check whether the number is valid pin code or not by using a Regular Expression. The valid pin code of India must satisfy the following conditions. It can be only six digits.It should not start with zero.First digit of the pin cod
6 min read
How to validate MAC address using Regular Expression
Given string str, the task is to check whether the given string is a valid MAC address or not by using Regular Expression. A valid MAC address must satisfy the following conditions: It must contain 12 hexadecimal digits.One way to represent them is to form six pairs of the characters separated with
6 min read
How to validate CVV number using Regular Expression
Given string str, the task is to check whether it is a valid CVV (Card Verification Value) number or not by using Regular Expression. The valid CVV (Card Verification Value) number must satisfy the following conditions: It should have 3 or 4 digits.It should have a digit between 0-9.It should not ha
5 min read
How to validate image file extension using Regular Expression
Given string str, the task is to check whether the given string is a valid image file extension or not by using Regular Expression. The valid image file extension must specify the following conditions: It should start with a string of at least one character.It should not have any white space.It shou
5 min read
Validate Phone Numbers ( with Country Code extension) using Regular Expression
Given some Phone Numbers, the task is to check if they are valid or not using regular expressions. Rules for the valid phone numbers are: The numbers should start with a plus sign ( + )It should be followed by Country code and National number.It may contain white spaces or a hyphen ( - ).the length
5 min read
How to validate ISIN using Regular Expressions
ISIN stands for International Securities Identification Number. Given string str, the task is to check whether the given string is a valid ISIN(International Securities Identification Number) or not by using Regular Expression. The valid ISIN(International Securities Identification Number) must sati
6 min read
How to validate PAN Card number using Regular Expression
Given string str of alphanumeric characters, the task is to check whether the string is a valid PAN (Permanent Account Number) Card number or not by using Regular Expression.The valid PAN Card number must satisfy the following conditions: It should be ten characters long.The first five characters sh
6 min read
How to validate Visa Card number using Regular Expression
Given a string str, the task is to check whether the given string is a valid Visa Card number or not by using Regular Expression. The valid Visa Card number must satisfy the following conditions: It should be 13 or 16 digits long, new cards have 16 digits and old cards have 13 digits.It should start
6 min read
Regular Expressions to Validate ISBN Code
Given some ISBN Codes, the task is to check if they are valid or not using regular expressions. Rules for the valid codes are: It is a unique 10 or 13-digit.It may or may not contain a hyphen.It should not contain whitespaces and other special characters.It does not allow alphabet letters. Examples:
5 min read