JavaScript-compatible regex reference

Hex Color Regex Pattern & Tester

Validate CSS hexadecimal color notation with a leading # and 3, 4, 6, or 8 hexadecimal digits. This covers short and long RGB forms plus the short and long forms that include an alpha channel.

Pattern

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

Flags: i

Live test vectors

Test the Hex color regex

Enter one value per line. Each line is tested against the whole-string pattern using the browser JavaScript RegExp engine.

PASS#fff
PASS#0f08
PASS#FF5733
PASS#336699cc
FAILfff
FAIL#12
FAIL#12345
FAIL#gggggg

Quick answer

CSS hex colors start with # and use exactly 3, 4, 6, or 8 hexadecimal digits. The four- and eight-digit forms include alpha; other lengths should be rejected.

Common use cases

  • Theme and design-token validation
  • Color-picker form checks
  • CSS configuration imports

Pitfalls and limitations

  • !Forgetting the 4- and 8-digit alpha forms rejects valid CSS colors.
  • !A six-digit-only pattern is appropriate only when your product intentionally disallows shorthand and alpha.
  • !Regex checks syntax only; it does not convert between hex, RGB, HSL, or named colors.

Known-valid examples

#fff#0f08#FF5733#336699cc

Known-invalid examples

fff#12#12345#gggggg

Continue testing and debugging

Frequently asked questions

Why are 4-digit and 8-digit hex colors valid?

They add an alpha component to the short and long RGB forms. The fourth or eighth byte-pair position represents opacity.

Should hex color matching be case-sensitive?

No. Hexadecimal digits A–F can be uppercase or lowercase, so the page uses case-insensitive matching.

Does this pattern accept CSS named colors such as red?

No. It validates hexadecimal color notation only. Named colors, rgb(), hsl(), and other CSS color syntaxes are separate formats.