Regex for Hex Color Codes
CSS hex colors come in a 3-digit shorthand (#fff) and the full 6-digit form (#1a2b3c). This pattern accepts exactly those two, hash required. The alternation order doesn't matter here because the anchors force a full-string match — a 6-digit color can't half-match the 3-digit branch.
/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/How it works, token by token
| Token | Meaning |
|---|---|
| ^# | start of string, then the literal hash |
| (?: | non-capturing group for the two length alternatives |
| [0-9a-fA-F]{3} | shorthand: exactly 3 hex digits (#fff) |
| |[0-9a-fA-F]{6} | or the full form: exactly 6 (#1a2b3c) |
| )$ | close the group, end of string |
What it matches
#fff#1a2b3c#00FF00fff#12345#gggTry it live
One candidate per line — the m flag makes the ^ and $ anchors apply to each line. Edit anything; it runs in your browser.
Variations
^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$CSS Color 4: also accepts #rgba and #rrggbbaa alpha forms^#?(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$hash optional — for inputs where users paste bare hexFrequently asked questions
Why not just [0-9a-fA-F]{3,6}?
A range quantifier would also accept 4- and 5-digit strings like #1234, which aren't valid classic hex colors (4 digits is valid only as the #rgba alpha shorthand). The alternation pins the lengths to exactly 3 or 6.
Does this validate that the color looks right?
It validates syntax only — #000000 and #010101 are both just valid strings to a regex. For contrast checking or palette work, parse the channels and do the math (or use a color tool).
Building something custom? The regex tester gives you live match highlighting for any pattern.