Regex for hex color code

Use /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/ to check that a whole string is a valid for hex color code. Every example below is tested against the pattern, and you can open it in the Regex Tester with the samples preloaded.

Updated

/^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/
Open in Regex Tester
InputResult
#fff✓ Match
#1A2B3C✓ Match
#1a2b3c80✓ Match
#f0f8✓ Match
1a2b3c✗ No match
#12345✗ No match
#ggg✗ No match
#1234567✗ No match

How the pattern works

PartMeaning
^#Starts with #
[0-9a-fA-F]{3,4}Short form: #rgb or #rgba
[0-9a-fA-F]{6}Full form: #rrggbb
[0-9a-fA-F]{8}Full form with alpha: #rrggbbaa

Code examples

JavaScript

const re = /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
re.test(value); // true or false

Python

import re

bool(re.fullmatch(r'#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})', value))

PHP

preg_match('/^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/', $value) === 1;

Notes and limitations

All four lengths are valid CSS. Remove the {3,4} and {8} alternatives if your system only accepts six-digit colors. Convert between formats with the Color Converter.

Regex TesterType a pattern and watch matches highlight live in your test text.
Open the tool

Frequently asked questions

What is the regex for hex color code?
/^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/ — it matches the whole string. See the table above for what each part does.
Which examples match?
Of the examples tested, these match: #fff, #1A2B3C, #1a2b3c80, #f0f8. The others don’t.
How do I test this regex?
Click “Open in Regex Tester” — the pattern, flags and sample text load automatically, and matches highlight as you edit.