Pattern library / Validation
Hex Color Regex (#RGB and #RRGGBB)
CSS accepts #abc and #aabbcc — and design tools emit both, sometimes with the hash stripped. One compact alternation validates either length, any letter case, hash optional.
How the pattern works
#?— the hash is optional, so it accepts both4f8ef7and#4f8ef7.- The alternation enforces length: exactly 3 or exactly 6 hex digits — 4, 5, 7 and 8 fail.
- 8-digit hex (
#rrggbbaa, alpha) is increasingly common — add{8}to the alternation if your toolchain emits it. - CSS named colors (
rebeccapurple) are a lookup table, not a regex problem.
Test it: match & no-match examples
Every row is loaded straight into the tester — click Try to see the match live:
| Input | Result | Why | |
|---|---|---|---|
#4f8ef7 | Match | 6-digit with hash | Try → |
#abc | Match | 3-digit shorthand | Try → |
4F8EF7 | Match | hash optional | Try → |
#ff0000ff | No match | 8-digit (RGBA) not matched | Try → |
#abcde | No match | 5 digits invalid | Try → |
rgb(79,142,247) | No match | rgb() notation, not hex | Try → |
Where to use it
JavaScript
const HEX = /^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
HEX.test('#4f8ef7'); // true
Python (design-token audit)
import re
HEX = r'^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$'
bad = [c for c in tokens if not re.fullmatch(HEX, c)]
BigQuery / GA4 (RE2)
REGEXP_CONTAINS(value, r'^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$')
Common mistakes
- Anchors matter: without them #abc matches inside #abcde fragments — strip or keep based on find-vs-validate.
- Lowercase-only input? [0-9a-f] is marginally stricter and faster.
- HSL/rgb()/oklch() values are separate formats — extend the alternation, do not shoehorn them into the hex branch.
FAQ
How do I match 8-digit hex colors with alpha?
Add the length to the alternation: ^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$.
Does this regex require the # sign?
No — #? makes it optional, so both #aabbcc and aabbcc match. Remove #? if your input must always carry the hash.
Is this RE2 compatible for GA4 or BigQuery?
Yes — literal characters, quantifiers and alternation only, valid in every RE2-based engine.
Related patterns
UUID Regex — Match Any UUID (1-5) Format · Quoted String Regex — Match "..." and '...' · SemVer Regex — Match Semantic Versioning (2.0.0)
For GA4-specific patterns, see the GA4 regex cheat sheet, the page path regex guide, the event filter regex guide, the GA4 regex match types, the custom channel grouping guide and RE2 vs PCRE. Browse the full regex pattern library.