Validate Hex Color Code

This program validates hex color code using regex.

Problem Statement

Write a Java program to validate "#1A2B3C".

Source Code

1 public class RegexHexColorValidation {
2 public static void main(String[] args) {
3 System.out.println("Eduinq Regex Hex Color Validation");
4 String color="#1A2B3C";
5 String regex="^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$";
6 if(color.matches(regex)) System.out.println("Valid hex color");
7 else System.out.println("Invalid hex color");
8 }
9 }

Program Output

Eduinq Regex Hex Color Validation
Valid hex color

Explanation

Regex checks 3 or 6 hex digits. - Ensures proper hex color format. - Together validates hex color code. Conclusion: Shows how to validate hex color using regex.

Quick Links to Explore