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
Email Address /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/ URL /^https?:\/\/(www\.)?[a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([a-zA-Z0-9()@:%_+.~#?&/=-]*)$/ Phone Number (International) /^\+?[1-9]\d{1,14}$/ Phone Number (US) /^\(?[2-9]\d{2}\)?[-.\s]?\d{3}[-.\s]?\d{4}$/ Phone Number (EU) /^\+?[1-9][0-9]{0,3}[\s.-]?\(?[0-9]{1,5}\)?[\s.-]?[0-9]{1,5}[\s.-]?[0-9]{1,5}$/ IPv4 Address /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/
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.