Back to Pattern Library
Web Development

Match Hex Color Code Regex

A regex pattern to identify valid 3-digit and 6-digit hexadecimal color codes used in CSS.

Loading Regex Sandbox...

How to Match CSS Hex Colors with Regex

Hexadecimal color codes are the foundation of web design. They always start with an optional # symbol, followed by either 3 or 6 alphanumeric characters ranging from A-F and 0-9.

The Pattern Breakdown

The regular expression ^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$ ensures absolute CSS validity:

  • ^#?: The hash symbol is optional, meaning it matches both #FFF and FFF.
  • [a-fA-F0-9]{6}: Checks for exactly 6 valid hex characters (e.g., FF5733).
  • |: The logical OR operator.
  • [a-fA-F0-9]{3}: Checks for the shorthand 3-character format (e.g., F00).

Common Use Cases

  • CSS Minifiers: Finding and compressing 6-digit hex codes to their 3-digit shorthand.
  • Design Tools: Validating user input in color picker UI components.
  • Web Scrapers: Extracting brand color palettes from external stylesheets.