How the pattern works
| Part | Meaning |
|---|---|
^# | Starts with # |
[0-9a-fA-F]{3,4} | Short form: #rgb or #rgba |
[0-9a-fA-F]{6} | Full form: #rrggbb |
[0-9a-fA-F]{8} | Full form with alpha: #rrggbbaa |
Code examples
JavaScript
const re = /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
re.test(value); // true or falsePython
import re
bool(re.fullmatch(r'#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})', value))PHP
preg_match('/^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/', $value) === 1;
Notes and limitations
All four lengths are valid CSS. Remove the {3,4} and {8} alternatives if your system only accepts six-digit colors. Convert between formats with the Color Converter.
Regex TesterType a pattern and watch matches highlight live in your test text.
Open the tool Frequently asked questions
What is the regex for hex color code?
/^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/ — it matches the whole string. See the table above for what each part does.
Which examples match?
Of the examples tested, these match: #fff, #1A2B3C, #1a2b3c80, #f0f8. The others don’t.
How do I test this regex?
Click “Open in Regex Tester” — the pattern, flags and sample text load automatically, and matches highlight as you edit.