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

PartMeaning
^#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

InputMatch?Note
#FF5733YesValid format
#fffYesValid format
#1a2b3cYesValid format
#GGGGGGNoG is not a valid hex character
FF5733NoMissing 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

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.

Built by Michael Lip. 100% client-side — no data leaves your browser.