T
ToolPrime

Regex for Hex Color Code

Validates CSS hex color codes in 3-digit or 6-digit format.

Pattern

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

Live Tester

Enter a string to test

Examples

The i flag makes the pattern case-insensitive.

#fff
#FF5733
#000000
#gg0000
FF5733
#12345

Pattern Breakdown

^# — starts with hash

([0-9a-fA-F]{3} — 3 hex digits (shorthand)

|[0-9a-fA-F]{6})$ — or 6 hex digits

Code Snippets

Javascript

const regex = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/i;
regex.test("#FF5733"); // true

Python

import re
pattern = r"^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$"
bool(re.match(pattern, "#FF5733", re.IGNORECASE))  # True

Php

$pattern = '/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/i';
preg_match($pattern, "#FF5733"); // 1

Related Patterns

Frequently Asked Questions

What is the regex for Hex Color Code?
The regex pattern for Hex Color Code is /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/i. Validates CSS hex color codes in 3-digit or 6-digit format.
How do I use the Hex Color Code regex in JavaScript?
In JavaScript you create the pattern with a regex literal or the RegExp constructor and call .test() to check a string against it. A ready-to-copy example is shown in the Code Snippets section above, alongside Python and PHP versions.
What does the Hex Color Code pattern match?
It matches strings like #fff; it rejects strings like #gg0000. See the Examples section above for the full list of matching and non-matching cases.

Related Tools