regexhelper
Test a pattern. Copy a ready-made one. No signup.

Regex to Match a Hex Color Code

Copy the pattern, paste your CSS below, and watch it highlight every hex color. Below the tester: which lengths it accepts and how to make it case-sensitive.

/ /

What this pattern matches

This expression matches CSS hex colors in all four common lengths: 3-digit (#fff), 4-digit with alpha (#fffa), 6-digit (#1a2b3c), and 8-digit with alpha (#1a2b3cff).

How it works, part by part

# — the literal hash that starts a hex color.

[0-9a-fA-F]{3,4} — three or four hex digits (short form, optional alpha).

[0-9a-fA-F]{6} or {8} — the six- or eight-digit long form.

\b — a word boundary so #12345 (5 digits) does not partially match.

Case and boundaries

The class includes both a-f and A-F, so #ABC and #abc both match. If your stylesheet only uses lowercase, drop A-F to enforce it.

FAQ

Does it match 8-digit colors with alpha?

Yes. #RRGGBBAA like #1a2b3cff matches via the {8} alternative.

Why does #12 not match?

The shortest accepted form is 3 hex digits, so #12 (two digits) fails.

How do I match colors without the # too?

Make the hash optional by wrapping it as #? — but be aware that raw hex sequences then match a lot of unrelated text.