Start free · Free tools · Fair usage limits
Browse Tools

Categories

Custom AI Solutions – AI2Flows
LIVE NEWS
Loading latest AI & SEO news…
Home›Tools›Regex Tester›Regex for hex color code
Regex pattern · validation

Regex for hex color code

Regex for hex color: a tested pattern with examples, a plain-English breakdown, and code for JavaScript, Python, PHP, Java and Go.

Quick answer

Use /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/ as a hex color code regex. It matches "#fff" and "#1a2b3c", and rejects "fff" and "#ggg". Make the # optional with ^#? if users paste colors without it.

Last updated · Maintained by FreeAIToolz · How we test

/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/
  • #fffmatches
  • #1a2b3cmatches
  • #1a2b3cffmatches
  • #FFFAmatches
  • fffno match
  • #gggno match
  • #12345no match
  • #1234567no match
Open in the full Regex Tester (replace, flags, groups) →

How this regex works

PartMeaning
^#hash
[0-9a-fA-F]{3}|{4}short form, optionally with alpha
[0-9a-fA-F]{6}|{8}long form, optionally with alpha

Examples

InputResult
#fff✓ Matches
#1a2b3c✓ Matches
#1a2b3cff✓ Matches
#FFFA✓ Matches
fff✗ No match
#ggg✗ No match
#12345✗ No match
#1234567✗ No match

Every example above is checked automatically in JavaScript and Python each time the site is built.

Limitations and edge cases

Make the # optional with ^#? if users paste colors without it.

When to use this pattern

Theme settings, design tokens and color pickers.

Use it in your language

JavaScript

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

Python

import re
pattern = re.compile(r'^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$')
bool(pattern.search(value))

PHP

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

Java

Pattern pattern = Pattern.compile("^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$");
boolean ok = pattern.matcher(value).find();

Go

re := regexp.MustCompile(`^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$`)
ok := re.MatchString(value)

More regex patterns

Frequently asked questions

What is the regex for hex color code?
/^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/. Make the # optional with ^#? if users paste colors without it.
Which languages does this pattern work in?
It is tested in JavaScript and Python and uses syntax that also works in PHP (PCRE) and Java. It also works in Go’s RE2 engine.
Why does the pattern start with ^ and end with $?
They anchor the match to the whole string, so "abc#fffxyz" cannot pass just because it contains a valid part. To search for matches inside longer text, remove ^ and $ (use \b where word boundaries help) and add the g flag.