Hex color regex
A # followed by 3, 4, 6 or 8 hex digits — the short and long forms CSS accepts, with or without alpha. Copy the pattern, with 4 inputs it accepts and 5 it rejects, each checked against it at build time.
Part of developer tools.
^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/iFlags: i
What the hex color regex accepts and rejects
Each result below is the output of the pattern itself, run on the input when this page was built — not a claim copied next to it. A wrong verdict stops the build.
| Input | Result | Why |
|---|---|---|
| #fff | Passes | three-digit short form |
| #7C5CFF | Passes | six digits, upper case |
| #ff7f50cc | Passes | eight digits, with alpha |
| #0f08 | Passes | four-digit short form with alpha |
| fff | Fails | no # |
| #ff7f5 | Fails | five digits |
| #ff7f50c | Fails | seven digits |
| #ggg | Fails | g is not a hex digit |
| # fff | Fails | a space after the # |
Limits
- Only the hex notation is covered. CSS also accepts rgb(), hsl(), oklch() and named keywords such as coral, none of which a single regex handles well — parse them instead.
- Alpha forms (#rgba, #rrggbbaa) are accepted; refuse them by dropping the 4 and 8 alternatives if the target does not support transparency.
Try it on your own input
Open this pattern in the regex tester with every example above on its own line. The link adds the g and m flags so that ^ and $ hold per line and every line is tested: the highlighted lines are the ones marked as passing here. Paste your own data in place of the examples — it is matched in your browser and never uploaded.
Other common regexes
- Email address
- URL
- UUID
- IPv4 address
- ISO 8601 date
- 24-hour time
- Semantic version
- URL slug
- Phone number (E.164)
- US ZIP code
- MAC address
Or open the regex tester empty and bring your own pattern.