Regex to Match Hex Color Codes

Validate CSS hex color codes with this regex pattern. Matches 3-digit, 6-digit, and 8-digit (with alpha) hex colors like #FFF or #FF5733CC.

Regular Expression

/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/i

Token Breakdown

TokenDescription
^Anchors at the start of the string (or line in multiline mode)
#Matches the literal character '#'
(?:Start of non-capturing group
[0-9a-fA-F]Character class — matches any one of: 0-9a-fA-F
{3}Matches exactly 3 times
|Alternation — matches the expression before OR after the pipe
[0-9a-fA-F]Character class — matches any one of: 0-9a-fA-F
{6}Matches exactly 6 times
|Alternation — matches the expression before OR after the pipe
[0-9a-fA-F]Character class — matches any one of: 0-9a-fA-F
{8}Matches exactly 8 times
)End of group
$Anchors at the end of the string (or line in multiline mode)

Detailed Explanation

This regex validates CSS hex color codes in their standard formats. Here is the token-by-token breakdown:

^ — Anchors the match at the start of the string.

— Matches the literal hash symbol that prefixes all CSS hex color codes.

(?: — Opens a non-capturing group with three alternatives for valid hex color lengths.

[0-9a-fA-F]{3} — The first alternative matches 3-digit shorthand hex colors. Each digit is doubled to produce the full color value. For example, #F0A expands to #FF00AA. Valid characters are hexadecimal digits: 0-9 and a-f (both cases).

| — Alternation separator.

[0-9a-fA-F]{6} — The second alternative matches standard 6-digit hex colors. Two hex digits each for red, green, and blue channels. For example, #FF5733.

| — Alternation separator.

[0-9a-fA-F]{8} — The third alternative matches 8-digit hex colors that include an alpha (transparency) channel. The first six digits are RGB and the last two are the alpha value. For example, #FF5733CC.

) — Closes the non-capturing group.

$ — Anchors the match at the end of the string.

The i flag makes matching case-insensitive. This pattern covers all three valid hex color formats used in CSS. The 3-digit format is a shorthand, the 6-digit format is the most common, and the 8-digit format adds transparency support. Colors like #FFF, #ff5733, and #FF5733CC all match.

Example Test Strings

InputExpected
#FF5733Match
#fffMatch
#FF5733CCMatch
FF5733No Match
#GGHHIINo Match
#12345No Match

Try It — Interactive Tester

//i
gimsuy
No matches found.
Pattern: 51 charsFlags: iMatches: 0

Ctrl+Shift+C to copy regex

Customize this pattern →