Hex Color CodeRegex — Pattern, Examples & Code
^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$What it matches / doesn't match
| Matches ✅ | Does not match ❌ |
|---|---|
●#FF5733 | ●FF5733 |
●#fff | ●#GGHHII |
●#0a0a0a | ●#12345 |
How it works
Matches CSS hex color codes in both 3-digit shorthand (#RGB) and 6-digit (#RRGGBB) forms. The # prefix is required, and all characters must be valid hex digits (0–9, A–F). It does not match 8-digit hex colors with alpha (#RRGGBBAA) — extend the alternation if you need those.
Code Usage
JavaScript
const regex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
regex.test("#FF5733"); // truePython
import re
pattern = re.compile(r'^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$')
bool(pattern.match("#FF5733")) # TrueGo
import "regexp"
r := regexp.MustCompile(`^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$`)
r.MatchString("#FF5733") // trueNeed a custom regex for a different use case?
Generate a custom regex with AI →FAQ
What does the Hex Color Code regex pattern match?
Matches CSS hex color codes in both 3-digit shorthand (#RGB) and 6-digit (#RRGGBB) forms. The # prefix is required, and all characters must be valid hex digits (0–9, A–F). It does not match 8-digit hex colors with alpha (#RRGGBBAA) — extend the alternation if you need those.
How do I use the Hex Color Code regex in JavaScript?
const regex = /^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/; regex.test("#FF5733"); // true
Can I use the Hex Color Code regex in Python?
Yes. import re pattern = re.compile(r'^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$') bool(pattern.match("#FF5733")) # True
