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.

Regex pattern

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

This matches a CSS hex colour such as #fff, #abcd, #1a2b3c or #1a2b3c80 (3, 4, 6 or 8 hex digits). It validates the syntax, not whether the colour is the one you intend.

/ /

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.

Use it in your code

Python
import re
text = "Valid: #fff, #1a2b3c, #ffcc00aa, #ABC. Not a color: #12, #ghijkl (non-hex letters)."
pattern = r'''#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})\b'''
for m in re.finditer(pattern, text):
    print(m.group())
JavaScript
const text = "Valid: #fff, #1a2b3c, #ffcc00aa, #ABC. Not a color: #12, #ghijkl (non-hex letters).";
const re = new RegExp(String.raw`#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})\b`, "g");
console.log(text.match(re));

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.