Regex for Hex Color

All patterns
Validation37 chars

Regex for Hex Color

A simple validator for 3- or 6-digit hex colors, useful in design tooling and theme settings.

The expression

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

How to read it

Anchor: the match must start at the beginning of the string.

Anchor: the match must run to the end of the string.

A brace quantifier fixes how many times the previous token repeats.

(?: … ) groups without capturing, so it costs nothing to read back.

Validate your own text, line by line

no input
Try:

This expression is anchored, so it asks whether a whole string is valid. Each line above is tested on its own — it will not find a match inside a longer sentence.

Examples, checked in your browser

4/4 verified

#0fa

Matches.

3366FF

Matches.

#abcd

No match — this is the kind of input the pattern rejects.

rgb(0,0,0)

No match — this is the kind of input the pattern rejects.

Use it in code

3 languages
JavaScript
const regex = /^#?(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/g;
regex.test(input);
Python
import re
pattern = re.compile(r"^#?(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$")
bool(pattern.search(input))
Go
re := regexp.MustCompile("^#?(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$")
matched := re.MatchString(input)

Other validation patterns

6
GroupValidation
Flagsnone
Examples4
SafetyOK