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)

Related patterns

Try any pattern live in the Regex Tester