← Back to all regex patterns
Validation
Low backtracking risk

Regex for Hex Color

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

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

Try this pattern

Matches current input
#0fa

1 match found in the current text.

Passing examples

  • #0fa
  • 3366FF

Failing examples

  • #abcd
  • rgb(0,0,0)

Code examples

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)

Related Validation Patterns