DevKits

Validation

Match a CSS hex color

Flags: gi

Match CSS hex colors: #RGB, #RRGGBB, or #RRGGBBAA.

Pattern

Regular expression

#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3})\b

How it works

Order matters: try 8-digit (RGBA) then 6-digit (RGB) then 3-digit shorthand. The word boundary prevents partial matches inside longer hex strings.

Matches

  • #fff
  • #3B82F6
  • #3B82F680

Non-matches

  • #12345 (5 digits)
  • 3B82F6 (no hash)

Language snippets

JavaScript

const re = /#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3})\b/gi;

Python

re.findall(r"#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3})\b", text, re.I)

Go

re := regexp.MustCompile(`(?i)#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3})\b`)

Java

Pattern.compile("#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3})\\b", Pattern.CASE_INSENSITIVE)

Frequently asked questions

What is the regex for CSS hex color?

The pattern #(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3})\b (flags: gi) matches CSS hex color. Order matters: try 8-digit (RGBA) then 6-digit (RGB) then 3-digit shorthand. The word boundary prevents partial matches inside longer hex strings.

What does this CSS hex color pattern match?

It matches strings like #fff, #3B82F6, #3B82F680, but rejects #12345 (5 digits), 3B82F6 (no hash).

How do I use this pattern in JavaScript, Python, Go, Java?

Ready-to-run snippets are provided for JavaScript, Python, Go, Java. Copy the one for your language from the Language snippets section — each wraps the same core pattern in that language's regex API.

Related patterns

Try this pattern in a tool

Try any pattern live in the Regex Tester