New blogMaking an AI Agent You Can Trust With Money

★ Web · regex

Regex for Hex Color

Matches the four CSS hex colour forms, including the alpha variants.

  • Runs in your browser
  • No signup

Try the hex color pattern

Read it in plain English (best-effort)

  • ^start of a line
  • #the character '#'
  • (?:start a group (not captured)
  • [0-9a-fA-F]one character from: 0–9, a–f, A–F
  • {3}exactly 3 of the previous
  • |or
  • [0-9a-fA-F]one character from: 0–9, a–f, A–F
  • {4}exactly 4 of the previous
  • |or
  • [0-9a-fA-F]one character from: 0–9, a–f, A–F
  • {6}exactly 6 of the previous
  • |or
  • [0-9a-fA-F]one character from: 0–9, a–f, A–F
  • {8}exactly 8 of the previous
  • )end of group
  • $end of a line

One sample per line works well with the m flag on anchored patterns.

Waiting for a pattern
01

The pattern, piece by piece

/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/
Pattern explanation
PartWhat it does
^#starts with a hash
[0-9a-fA-F]{3}short form #rgb
[0-9a-fA-F]{4}short form with alpha #rgba
[0-9a-fA-F]{6}full form #rrggbb
[0-9a-fA-F]{8}full form with alpha #rrggbbaa
02

What it accepts and rejects

Every sample below is checked automatically in JavaScript and Python. The tester above is preloaded with all of them, one per line.

Should match
Should match
#fff✓
#FFFFFF✓
#1a2b3c✓
#abcd✓
#11223344✓
#0F0✓
Should not match
Should not match
fff✗
#ff✗
#fffff✗
#ggg✗
#1234567✗
# fff✗
03

Copy it into your code

RE2-safeNo lookarounds or backreferences, so the same pattern works in Go's RE2 engine and in Rust's regex crate.

const hexColorRe = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;

export function isValidHexColor(value) {
  return hexColorRe.test(value.trim());
}
04

When not to use regex for this

If you accept any CSS colour (rgb(), hsl(), named colours), use CSS.supports('color', value) in the browser instead of trying to regex every syntax.

05

Questions engineers actually ask

Should I accept colours without the #?
Normalise first: if the value is 3, 4, 6 or 8 hex characters, prepend # and then validate.
Is #abcd a valid colour?
Yes. It's the short form with alpha, supported by all modern browsers.
What is catastrophic backtracking?
Some patterns, usually nested quantifiers like (a+)+, make a backtracking engine try an exponential number of paths on input that almost matches. The tester stops any run after 300ms, so a bad pattern can't freeze your tab. In production, that same pattern can take down a server (a ReDoS attack).
06

More web patterns

07

More from the workbench

Fine print

Tools: on the house.
Engineer: by the hour.

The regex was free. Code that doesn't need one is the upgrade: typed schemas, validated once at the edge, trusted everywhere after.

I'm Himanshu, an AI and full-stack engineer. I build MVPs, AI agents and the growth plumbing around them for early-stage startups.