~/regex-tester

Match hex color codes with regex

A regex that captures #abc and #abcdef hex color codes from CSS, with optional 8-digit alpha variants.

# pattern

/#(?:[0-9a-f]{3}){1,2}\b/gi

→ Open in regex tester (pre-filled)

# how it works

The hash followed by either three or six hex digits. The `{1,2}` quantifier multiplies a 3-digit group, so it matches either #rgb or #rrggbb. To include 8-digit alpha codes, change to `#(?:[0-9a-f]{3,4}|[0-9a-f]{6,8})\b`.

# sample input

red #f00, blue #0000ff, accent #ff8800, brand #c4c — also 8-digit alpha: #ff8800aa.

# pitfalls

# other patterns