Regex Pattern

Hex Color Code Regex (CSS)

By Samrat•Last updated: Nov 2026
Regex Pattern
^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$

Quick answer

This regex matches standard CSS hex color codes. It allows an optional # symbol, followed by either 6 hex characters or 3 shorthand hex characters.

🛠️ Fix it right here with AI Regex Generator

Need to modify this pattern or generate a new one? Edit the regex below and let our AI help.

AI suggestions can be wrong. Review and test before applying.

Live Regex Tester

Type a string below to see if it matches this pattern.

How it works

^#? matches an optional hash. ([a-fA-F0-9]{6}|[a-fA-F0-9]{3}) matches either 6 characters or 3 characters. The $ ensures the entire string is just the color code.

Code Examples

✅ Correct Usage

// JavaScript
const hexRegex = /^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/;
console.log(hexRegex.test("#ffffff")); // true
console.log(hexRegex.test("000")); // true
console.log(hexRegex.test("#gggggg")); // false

❌ What NOT to do

// BAD: Doesn't allow 3-digit shorthand colors like #fff
const badRegex = /^#[a-fA-F0-9]{6}$/;

Frequently asked questions

Does this handle RGBA?

No, RGBA uses a different format like rgba(255, 255, 255, 0.5). This regex is only for hex codes.

Related Search Terms

hex color regexcolor code regexregex hexvalidate hex color

Related Regex Patterns

Need a custom regex pattern?

Use the free to describe what you need in plain English.

Want an AI with memory for your project?

MonsterX AI remembers your codebase across chats.