Formathex color regex

Hex color regex

CSS hex color in 3-, 6-, or 8-character (with alpha) form.

Pattern
/^#(?:[0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i

What it matches

CSS allows hex colors in three shapes: `#rgb` (4 bits per channel, expanded by doubling), `#rrggbb` (8 bits per channel), and `#rrggbbaa` (8 bits per channel plus alpha). This pattern accepts all three with the leading `#` required.

Examples

Matches

  • #fff

    3-digit shorthand for `#ffffff` (white).

  • #0a0a0a

    6-digit form (the tooled.dev brand background).

  • #0a0a0aff

    8-digit form with fully-opaque alpha.

Does not match

  • fff

    Missing leading `#`.

  • #0a0a

    Four digits is not a valid CSS hex length.

  • #zzzzzz

    Non-hex characters.

  • rgb(255, 0, 0)

    Different color syntax — needs its own pattern.

Edge cases & gotchas

  • Doesn't validate that the color makes sense for accessibility — `#000` on a `#001` background passes the regex but fails WCAG. Use a contrast checker (we ship one in our Color Toolkit).
  • Doesn't accept the 4-digit short form `#rgba` — modern CSS allows it. Add `[0-9a-f]{4}` to the alternation if you want.
  • Case is fine either way (`i` flag) but most style guides prefer lowercase. Normalize with `.toLowerCase()`.

In your language

// JavaScript
const re = /^#(?:[0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
const match = "input".match(re);

All 13 languages (including Bash, Perl, Kotlin, Swift) available in the full toolkit Export tab.

Notes for production

  • CSS Module 4 introduced `oklch()` and `color()` — for new work in a perceptually-uniform color space, prefer those over hex.
  • Tailwind v4 expects modern color tokens but still accepts hex in arbitrary values like `bg-[#0a0a0a]`.

Frequently asked

Does this match `rgb()` or `hsl()` colors?

No — those are different CSS color syntaxes. Each needs its own pattern. A general-purpose CSS color regex needs to handle hex + rgb + rgba + hsl + hsla + named colors + oklch — much simpler to use a parser.

How do I extract every hex color from a CSS file?

Drop the `^` and `$`, add the `g` flag: `/#(?:[0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})\b/gi`. The word-boundary `\b` prevents matching inside larger hex tokens.

Why does `#abc` match but `#abcd` doesn't?

`#abc` is valid 3-digit CSS hex; `#abcd` would be 4-digit (rgba shorthand). Add `[0-9a-f]{4}` to the alternation if you need it.

Related patterns