Skip to main content
hank-builds.com

Hex Color regex

Matches 3 or 6 digit hex color codes.

/#(?:[0-9a-fA-F]{3}){1,2}\b/g

What it matches

A hash followed by three or six hexadecimal digits, so both the shorthand #f0c and the full #ff00cc. The {1,2} repetition of a three-digit group is what allows exactly those two lengths and nothing in between, and the trailing word boundary stops #abcd matching as #abc.

Railroad diagram

Read left to right. Every path through the diagram is a string the pattern accepts.

"#" {1,2}{3} [0-9a-fA-F] \b

Drag to pan. Ctrl+scroll to zoom.

Breakdown

gFind all matches instead of stopping after the first
#Literal "#"
[0-9a-fA-F]{3}Match one of: Literal "0"–Literal "9", Literal "a"–Literal "f", Literal "A"–Literal "F", exactly 3 times
\bWord boundary

Test cases

Matches

  • #fff
  • #3b82f6
  • #F0F

Does not match

  • fff
  • #12
  • #ggg

Caveats

CSS also allows four and eight digit hex for alpha (#f0cd, #ff00ccdd) and this rejects both. It does not match rgb(), hsl() or named colours. The word boundary is doing real work: without it the pattern would take the first six characters of any longer hex string, such as a commit SHA.

More web patterns

Test this against your own input in the regex tester, browse the full pattern library, or check the syntax cheat sheet.