Regex for hex colour codes (#fff, #1D9E75)

CSS hex colours start with a hash followed by three or six hexadecimal digits. This pattern matches both short and long forms.

The pattern

/#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{3})\b/g

The tester opens with this pattern and the examples below already loaded. Nothing you type is uploaded.

How it works

#
The leading hash.
[0-9a-fA-F]{6}
Six hex digits (#RRGGBB). Listed first so the long form wins.
[0-9a-fA-F]{3}
Three hex digits (#RGB shorthand).
\b
Boundary, so #12345 is not matched as #123 plus extra digits.

Examples

Matches

  • #fff
  • #1D9E75
  • #0F6E56

Does not match

  • #ggg
  • #12
  • fff
  • #12345

Use it in JavaScript

const re = /#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{3})\b/g;

// Find every match in a block of text
const found = text.match(re);

// Validate that a whole value matches (no stray characters around it)
const exact = new RegExp('^(?:' + re.source + ')$', re.flags.replace('g', ''));
const isValid = exact.test(value);

Limits and tips

  • To also accept transparency forms (#RGBA and #RRGGBBAA), use #(?:[0-9a-fA-F]{8}|[0-9a-fA-F]{6}|[0-9a-fA-F]{4}|[0-9a-fA-F]{3})\b.
  • The order of the alternatives matters: longer options go first, otherwise the engine matches the three-digit form inside a six-digit colour.

Frequently asked questions

Does it match colours without the hash?

No. The # is required. Make it optional with #? if you accept bare values, but then test strings carefully.

Why is the six-digit option listed first?

Regex alternation takes the first option that works, so putting the short form first would stop early on longer colours.