Regex for a hex colour code

A regular expression for hex colour codes as CSS accepts them: #rgb, #rgba, #rrggbb and #rrggbbaa, with a version for finding colours in a stylesheet.

//

Matches

This tool runs in your browser. We never send what you type or paste to a server.

The pattern

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

The CSS Color Module Level 4 defines four hex forms. Six digits give red, green and blue as two hex digits each. Three digits are a shorthand where each digit is doubled, so #3af is #33aaff. Eight and four digits add an alpha (opacity) channel at the end. All modern browsers support the four forms.

The tester at the top of this page is loaded with this pattern and the examples below, one per line. It adds the m flag so that ^ and $ apply to each line, and g to show every match. Edit either box to try your own input.

How it works, token by token

PartMeaning
^Start of the string.
#A literal hash.
(?:A group of three lengths:
[0-9a-f]{3,4}Three or four hex digits: #rgb or #rgba.
|or
[0-9a-f]{6}Six: #rrggbb.
|or
[0-9a-f]{8}Eight: #rrggbbaa.
)End of the group.
$End of the string. The i flag allows capitals.

What it matches and what it rejects

InputResultWhy
#fffmatchesThree digits.
#FFFmatchesCapitals.
#3a7bd5matchesSix digits.
#3A7BD580matchesEight: the last two are the alpha channel (80 hex is about 50% opacity).
#f0f8matchesFour: #rgba.
3a7bd5rejectedNo #.
#ffrejectedTwo digits.
#fffffrejectedFive.
#3a7bd5frejectedSeven.
#gggrejectedg is not hex.
#3a7bd5␣rejectedA trailing space.

The common 3-or-6 pattern

Many answers online give this shorter pattern. It is fine if your system cannot handle transparency, but it rejects the alpha forms:

/^#(?:[0-9a-fA-F]{3}){1,2}$/
InputResultWhy
#fffmatchesThree.
#3a7bd5matchesSix.
#3A7BD580rejectedEight-digit colours with alpha are rejected.
#f0f8rejectedSo are four-digit ones.

Order matters in the full pattern too. Inside an anchored pattern the engine backtracks until one alternative fits, so {3,4} first is safe. Without anchors, a shorter alternative can win too early, which is why the search pattern below lists the longest form first.

Finding colours in CSS

To list the colours in a stylesheet, drop the anchors, put the longest alternative first and end with \b so that a match cannot stop in the middle of a longer run of letters and digits:

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

Searching this text:

a { color: #333; background: #3a7bd580; border: 1px solid #CCCCCC; } #main, #face { }

finds 4 matches:

1. #333
2. #3a7bd580
3. #CCCCCC
4. #face

The last match shows the limit of a pattern: #face is an ID selector, but it is made only of hex letters, so to a regex it looks like a colour. #main is skipped because m is not a hex digit. To be certain, parse the CSS and look only at property values.

Normalising colours

The same colour can be written #FFF, #fff and #ffffff. Before comparing or storing, lowercase the value and expand the short forms by doubling each digit. To convert between hex, RGB and HSL, or check contrast between two colours, use the colour converter.

Browsers also accept named colours (rebeccapurple), rgb(), hsl() and newer functions such as oklch(). If users may enter any CSS colour, the most reliable test in a browser is CSS.supports('color', value), which asks the browser's own parser.

In JavaScript, Python, PHP and C#

JavaScript

const re = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
console.log(re.test('#fff')); // → true
console.log(re.test('3a7bd5')); // → false

Python

import re

pattern = re.compile(r'#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})', re.IGNORECASE)
print(bool(pattern.fullmatch('#fff')))  # → True
print(bool(pattern.fullmatch('3a7bd5')))  # → False

PHP

<?php
$pattern = '/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/iD';
echo preg_match($pattern, '#fff'), "\n"; // → 1
echo preg_match($pattern, '3a7bd5'), "\n"; // → 0

C#

using System;
using System.Text.RegularExpressions;

var pattern = new Regex(@"^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})\z", RegexOptions.IgnoreCase);
Console.WriteLine(pattern.IsMatch("#fff")); // → True
Console.WriteLine(pattern.IsMatch("3a7bd5")); // → False

Each version checks the whole string. JavaScript's $ only matches at the very end, but Python, PHP and .NET also let $ match just before a final line break, so "abc\n" could slip through. The Python version uses re.fullmatch (so the ^ and $ are dropped), PHP adds the D modifier, and C# ends with \z.

The JavaScript, Python and C# examples are run before each update and their output is compared with the comments. PHP is not installed on our build machine, so the PHP version is checked against the PCRE pattern modifier documentation, and its string literal is checked to hand PHP exactly the pattern tested here.

Questions

What is the regex for a hex colour code?

^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$ with the i flag accepts every hex form CSS supports. Use ^#(?:[0-9a-fA-F]{3}){1,2}$ if you want only #rgb and #rrggbb.

Should the # be optional?

Only if you add it back before using the value. CSS needs the #, so storing colours with it avoids confusion. To make it optional, write #? instead of #.

What do the last two digits of an eight-digit hex colour mean?

They are the alpha channel, from 00 (fully transparent) to ff (fully opaque). #3a7bd580 is the colour #3a7bd5 at about 50% opacity.