Advertisement

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.

The pattern
^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$
Load this pattern into the tester →

How the pattern works

Test it: match & no-match examples

Every row is loaded straight into the tester — click Try to see the match live:

InputResultWhy
#4f8ef7Match6-digit with hashTry →
#abcMatch3-digit shorthandTry →
4F8EF7Matchhash optionalTry →
#ff0000ffNo match8-digit (RGBA) not matchedTry →
#abcdeNo match5 digits invalidTry →
rgb(79,142,247)No matchrgb() notation, not hexTry →

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

Test this pattern on your own data
Paste it into the free tester with your real strings — nothing leaves your browser.
Open the regex tester →

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.

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.