RRegexBuilder
Get RegexBuilder

RegexBuilder · regex answers

Regex for a hex colour code

/^#([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i

CSS accepts four lengths: three digits, four with alpha, six, and eight with alpha. Ordering the alternatives longest-first is unnecessary here because the anchors force a full-string match, but it matters the moment you drop the $.

What each part does

#the literal hash
[0-9a-f]{3}shorthand, one hex digit per channel
[0-9a-f]{8}full form with an alpha channel
icase-insensitive — #FFF and #fff are the same colour

Tested against real input

Every row below was run through the engine when this page was built. The third column is the substring the pattern actually matched.

InputResultMatched
#fffmatches#fff
#FFFFmatches#FFFF
#a1b2c3matches#a1b2c3
#a1b2c3ffmatches#a1b2c3ff
fffno match
#ffno match
#12345no match
#ggggggno match

The mistake to avoid

Writing ^#[0-9a-f]{3,8}$ — that also accepts five and seven digits, which no browser understands.

Try it on your own text

Paste this pattern and your input, see each match highlighted with its capture groups, step through what the engine did, and get the equivalent syntax for JavaScript, Python, Java, Go and PCRE.

Open RegexBuilder

Other regex answers