Hex Color Regex
Regex for matching CSS hex color codes: #FFF, #FFFFFF, and #FFFFFF80 formats.
^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}|[A-Fa-f0-9]{8})$About this pattern
This validates CSS hex colours in all three lengths: three digits (#f00), six (#ff0000), and eight (#ff0000cc), the last carrying an alpha channel. It is anchored, so the whole string must be the colour — appropriate for validating a stored token or a form field rather than scanning a stylesheet.
The three-digit form is shorthand in which each digit is doubled, so #f00 and #ff0000 are the same colour. That expansion is worth doing before comparison, because otherwise identical colours look distinct. Four-digit shorthand with alpha (#f00c) also exists and is not matched here; add {4} to the alternation if you need it.
Eight-digit hex puts alpha last, and the value is hexadecimal rather than a decimal fraction — the cc in #ff0000cc is 204 out of 255, roughly 0.8, so it is not interchangeable with the 0.8 you would write in rgba(). Confusing the two is a routine source of colours that look slightly wrong.
Browser support for eight-digit hex is broad now, but if you support genuinely old browsers, rgba() is the safer form. And when auditing a codebase, normalise before deduplicating: the same colour appears as #FFF, #fff, #ffffff, and white, and only normalisation reveals how many distinct colours you actually have.
Worked examples
Accepts 3, 6, and 8 digit forms; the 8-digit variant carries an alpha channel.
Matches
- #fff
- #FFFFFF
- #a1b2c3
- #ffffffcc
Does not match
- fff
- #gggggg
- #ffff
- #12345
FAQ
What is the difference between #f00 and #ff0000?
Nothing — the three-digit form is shorthand where each digit is doubled. Expand before comparing, or identical colours will appear distinct.
How does eight-digit hex alpha work?
The final pair is a hexadecimal alpha value, so cc is 204 of 255 — roughly 0.8. It is not the same scale as the decimal alpha in rgba().
Does this match four-digit shorthand?
No. #f00c (shorthand with alpha) needs {4} added to the alternation.