gettoolz.app

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.

Pattern^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$
JavaScript literal/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/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.

Inputs tested against the Hex color regex
InputResultWhy
#fffPassesthree-digit short form
#7C5CFFPassessix digits, upper case
#ff7f50ccPasseseight digits, with alpha
#0f08Passesfour-digit short form with alpha
fffFailsno #
#ff7f5Failsfive digits
#ff7f50cFailsseven digits
#gggFailsg is not a hex digit
# fffFailsa 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

Or open the regex tester empty and bring your own pattern.