Regex tester / pattern library

Regex: hex color

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

How it works

A # followed by 3 (shorthand), 4 (shorthand+alpha), 6 (full), or 8 (full+alpha) hex digits — every form CSS accepts.

Honest caveats

CSS also allows colors without # in some attribute contexts, and named colors (rebeccapurple) obviously do not match. Match order in the alternation matters if you drop anchors.

Matches

  • #fff
  • #B87333
  • #1a2b3c80
  • #abcd

Doesn't match

  • fff
  • #ggg
  • #12345
  • #1234567

More patterns