Regex for Hex Color Codes — Pattern Explained with Examples
This regex validates hexadecimal color codes used in web design and graphics. It supports both the 6-digit (#RRGGBB) and 3-digit shorthand (#RGB) formats, with the # prefix being optional. This is one of the most commonly used patterns in front-end development for CSS color validation, color picker tools, and design system utilities.
The Pattern
/^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/Pattern Breakdown
| Part | Meaning |
|---|---|
^ | Start of string |
#? | Optional hash/pound sign prefix |
( | Start of alternation group |
[0-9a-fA-F]{3} | Exactly 3 hex digits (shorthand: e.g., F00 = #FF0000) |
| | OR |
[0-9a-fA-F]{6} | Exactly 6 hex digits (full: e.g., FF5733) |
) | End of alternation group |
$ | End of string |
Matches
#FF5733#abc123456#000#FFFFFF#f0f0f0ABC123
Does NOT Match
#FF573— 5 hex digits after##GGGGGG— G is not a valid hex character#1234— 4 hex digits after##ABCDE— 5 hex digits after###FF5733— double hashrgb(255,87,51)— RGB function, not hextransparent— named color, not a hex code#FFF(with trailing space) — trailing whitespace violates end anchor
Language Examples
JavaScript
const hexRegex = /^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
console.log(hexRegex.test('#FF5733')); // true
console.log(hexRegex.test('#abc')); // true
console.log(hexRegex.test('#GGGGGG')); // false
// Convert 3-digit to 6-digit
function expandHex(hex) {
const cleaned = hex.replace('#', '');
if (cleaned.length === 3) {
return cleaned[0] + cleaned[0] + cleaned[1] + cleaned[1] + cleaned[2] + cleaned[2];
}
return cleaned;
}
console.log(expandHex('#abc')); // aabbcc
Python
import re
hex_regex = r'^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$'
print(bool(re.match(hex_regex, '#FF5733'))) # True
print(bool(re.match(hex_regex, '#abc'))) # True
print(bool(re.match(hex_regex, '#GGGGGG'))) # False
# Convert 3-digit to 6-digit
def expand_hex(hex_code):
cleaned = hex_code.lstrip('#')
if len(cleaned) == 3:
return ''.join(c * 2 for c in cleaned)
return cleaned
print(expand_hex('#abc')) # aabbccCommon Pitfalls
3-digit shorthand expansion —
#F00is shorthand for#FF0000. Each hex digit doubles:#RGB→#RRGGBB. When processing, ensure you expand shorthand before converting to RGB values.Case insensitivity — Both uppercase (
#FF5733) and lowercase (#ff5733) are valid. The pattern uses[0-9a-fA-F]for case-insensitive matching, but you may need to normalize case before comparison.Optional
#prefix — CSS requires the#, but some color pickers and APIs accept raw hex values. The#?makes it optional. For CSS validation, remove the?to enforce the hash.Alpha channel not supported — CSS Color Level 4 introduces 8-digit hex (
#RRGGBBAA) for RGBA colors. To support it, extend the alternation:[0-9a-fA-F]{8}.
Real-World Use Cases
- Form validation — Accepting user-entered hex color codes in theme customizers
- Color picker tools — Validating user input alongside a visual color picker interface
- Design system utilities — Parsing and converting hex colors to RGB, HSL, or CSS variables
FAQ
Related Patterns
- Regex for Password Strength
- Regex for Username/Slug
- Regex for File Extension
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro