Skip to main content
Code & Markup · In-Browser Regular Expression Lab

Hex Color Regex — 3, 6, and 8-Digit Hex CSS Colors with Hash

Matches CSS hex colors in #RGB, #RRGGBB, and #RRGGBBAA (with alpha transparency) formats.

Flags:
//none
Match Found
Load Sample:
Match Inspection & Details1 match
Match #1:#ffffff

Test Samples Verification Matrix

Expected Valid Samples (Should Match)

#ffffff Pass
#3B82F6 Pass
#fff Pass
#10b98180 Pass

Expected Invalid Samples (Must Reject)

ffffff Rejected (Pass)
#ffff Rejected (Pass)
#1234567 Rejected (Pass)
#zzzzzz Rejected (Pass)
Code Implementation Generator
// JavaScript / TypeScript (ES6+)
const pattern = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
const text = "#ffffff";

const isMatch = pattern.test(text);
console.log("Is Match:", isMatch);

if (isMatch) {
  const matches = text.match(pattern);
  console.log("Matches:", matches);
}

Regular Expression Token Breakdown

Matches leading # followed by 3, 6, or 8 hexadecimal digits. Each component of the regular expression serves a distinct syntactical purpose as mapped below:

Token PatternName / ComponentFunction & Rule
^#Hash PrefixLiteral # symbol.
[0-9a-fA-F]{3}3-digit shorthande.g., #fff for #ffffff.
[0-9a-fA-F]{6}6-digit standardFull red, green, blue channels.
[0-9a-fA-F]{8}8-digit with AlphaAdds 2-digit alpha channel for opacity.

Frequently Asked Questions

How to make the # optional?
Change `^#` to `^#?`.
Browse All 40 Patterns