What Is a Good Regex for Hex Color Code Validation?
Pattern: ^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$. Hex color codes in CSS and web development use a # followed by 3 or 6 hexadecimal digits. The 3-digit shorthand (#RGB) expands each digit (e.g., #F0A becomes #FF00AA). Modern CSS also supports 4 and 8-digit hex for alpha transparency.
Breaking Down the Pattern
| Part | Meaning |
|---|---|
^# | Must start with a hash symbol |
[0-9a-fA-F]{3} | Short form: 3 hex characters (e.g., #FFF) |
| | OR |
[0-9a-fA-F]{6} | Long form: 6 hex characters (e.g., #FFFFFF) |
$ | End of string |
Test Cases
| Input | Match? | Note |
|---|---|---|
#FF5733 | Yes | Valid format |
#fff | Yes | Valid format |
#1a2b3c | Yes | Valid format |
#GGGGGG | No | G is not a valid hex character |
FF5733 | No | Missing the leading # symbol |
Usage Examples
JavaScript
const pattern = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
pattern.test('#FF5733'); // true
pattern.test('#GGGGGG'); // false
Python
import re
pattern = r'^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$'
bool(re.match(pattern, '#FF5733')) # True
bool(re.match(pattern, '#GGGGGG')) # False
Common Pitfalls
- This does not match 8-digit hex colors with alpha channel (#FF573380). Add |[0-9a-fA-F]{8} if needed.
- Some CSS contexts accept colors without # (e.g., in certain properties). Adjust the pattern if # is optional.
- Short form #RGB expands to #RRGGBB (e.g., #F00 = #FF0000), not #R0G0B0.
Try It Yourself
Test this regex with our Regex Tester.
Frequently Asked Questions
What is the difference between 3-digit and 6-digit hex colors?
A 3-digit hex color is a shorthand where each digit is doubled. #F0A is equivalent to #FF00AA. The 6-digit form provides the full 16.7 million color range.
Can hex colors have transparency?
Yes. CSS supports 4-digit (#RGBA) and 8-digit (#RRGGBBAA) hex colors. For example, #FF573380 is #FF5733 at 50% opacity.
Should I use hex or RGB in CSS?
Both are equivalent. Hex is more compact (#FF5733 vs rgb(255, 87, 51)), while RGB is easier to read. Modern CSS also supports hsl() which is more intuitive for color manipulation.