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
- Word boundary on the right prevents over-matching into surrounding hex strings, but a missing left anchor will match inside identifiers (use `\b#` if needed).
- 4-digit hex (#rgba) is a real CSS spec but rare in the wild — the 3-or-6 pattern is usually what you want.
- Named colors and rgb()/hsl() functions are different patterns. Combine with `|` if you need all three.