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
The regex requires a leading # followed by either exactly 6 or exactly 3 hexadecimal digits, and matches() validates the given string against this format, demonstrating hex color code validation.