Hex Color Code Regex Matching Guide
Learn how to validate and extract hex color codes using regular expressions, including 3-digit, 6-digit, and alpha channel formats.
Hex Color Code Regex Matching Guide
Hex color codes are the standard way to represent colors in web design and CSS. Whether you're validating user input, extracting colors from code, or building a design tool, regular expressions make hex color validation straightforward. In this guide, we'll explore patterns for matching various hex color formats.
Understanding Hex Color Codes
Hex color codes use hexadecimal notation (base-16) to represent RGB color values:
6-digit format: #RRGGBB (e.g., #FF5733)
3-digit shorthand: #RGB (e.g., #F53)
With alpha: #RRGGBBAA or #RGBA (e.g., #FF573380)
Each pair represents a color component:
- RR: Red (00-FF)
- GG: Green (00-FF)
- BB: Blue (00-FF)
- AA: Alpha/Transparency (00-FF)
Basic Hex Color Patterns
6-Digit Hex Color
^#[A-Fa-f0-9]{6}$
Valid Colors:
#FF5733#00FF00#123ABC
Breakdown:
^#- Start with # symbol[A-Fa-f0-9]{6}- Exactly 6 hex characters (0-9, A-F, a-f)$- End of string
Case-Insensitive Version
^#[0-9A-Fa-f]{6}$
Or use the i flag in your regex engine:
/^#[0-9A-F]{6}$/i
3-Digit Hex Color Shorthand
Basic 3-Digit Pattern
^#[A-Fa-f0-9]{3}$
Valid Colors:
#F53#ABC#09F
Note: #F53 is equivalent to #FF5533 (each digit is doubled)
Combined 3 and 6 Digit Pattern
^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$
Valid Colors:
#FF5733(6-digit)#F53(3-digit)
Breakdown:
^#- Start with #([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})- Either 6 or 3 hex characters$- End of string
Hex Colors with Alpha Channel
8-Digit with Alpha
^#[A-Fa-f0-9]{8}$
Valid Colors:
#FF573380(80 hex = ~50% opacity)#000000FF(fully opaque)#FF573300(fully transparent)
4-Digit with Alpha
^#[A-Fa-f0-9]{4}$
Valid Colors:
#F538(equivalent to #FF5533 + 88 alpha)
Universal Pattern (3, 4, 6, or 8 digits)
^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{8}|[A-Fa-f0-9]{3}|[A-Fa-f0-9]{4})$
Valid Colors:
#FF5733(6-digit)#FF573380(8-digit with alpha)#F53(3-digit shorthand)#F538(4-digit shorthand with alpha)
Extracting Hex Colors from Text
Find Hex Colors in Text
#[A-Fa-f0-9]{6}|#[A-Fa-f0-9]{3}
Extracts from CSS:
body {
background: #FF5733;
color: #FFF;
border: 1px solid #123ABC;
}
Result: #FF5733, #FFF, #123ABC
Find in Code (with word boundaries)
\b#[A-Fa-f0-9]{6}\b|\b#[A-Fa-f0-9]{3}\b
Prevents matching partial codes like #FF5733AA as #FF5733
Extract with Context
(#[A-Fa-f0-9]{6}|#[A-Fa-f0-9]{3})\s*(?::|;|=|\))
Captures: Hex color followed by CSS syntax (:, ;, =, or ))
Advanced Patterns
Valid Web-Safe Colors
^#([A-Fa-f0-9]{3}){1,2}$
Web-safe colors use only 00, 33, 66, 99, CC, FF for each component.
Exclude Named Colors
^#(?:[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$
Only matches hex codes, not named colors like red, blue, etc.
Match CSS Variables with Hex
--[\w-]+:\s*(#[A-Fa-f0-9]{6}|#[A-Fa-f0-9]{3})
Extracts: --primary-color: #FF5733 from CSS variables
Code Examples
JavaScript Validation
function isValidHexColor(color) {
const hexRegex = /^#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{3})$/i;
return hexRegex.test(color);
}
console.log(isValidHexColor('#FF5733')); // true
console.log(isValidHexColor('#F53')); // true
console.log(isValidHexColor('#GGGGGG')); // false
console.log(isValidHexColor('FF5733')); // false (missing #)
Extract from CSS
function extractHexColors(css) {
const hexRegex = /#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{3})/gi;
const colors = css.match(hexRegex) || [];
return [...new Set(colors)]; // Remove duplicates
}
const css = `
body { background: #FF5733; color: #FFF; }
.box { border: 1px solid #123ABC; background: #F53; }
`;
console.log(extractHexColors(css));
// Output: ['#FF5733', '#FFF', '#123ABC', '#F53']
Convert Hex to RGB
function hexToRgb(hex) {
const hexRegex = /^#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{3})$/i;
if (!hexRegex.test(hex)) {
throw new Error('Invalid hex color');
}
// Expand shorthand
if (hex.length === 4) {
hex = '#' + hex[1] + hex[1] + hex[2] + hex[2] + hex[3] + hex[3];
}
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
return { r, g, b };
}
console.log(hexToRgb('#FF5733'));
// Output: { r: 255, g: 87, b: 51 }
Best Practices
1. Validate Before Processing
// GOOD: Validate first
if (isValidHexColor(color)) {
processColor(color);
} else {
showError('Invalid hex color code');
}
// BAD: Process without validation
processColor(color);
2. Use Capture Groups
const colorRegex = /^#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{3})$/i;
const match = color.match(colorRegex);
if (match) {
const hexValue = match[1]; // Capture hex without #
console.log(hexValue);
}
3. Handle Case Sensitivity
// Option 1: Use case-insensitive flag
const regex = /^#[0-9A-F]{6}$/i;
// Option 2: Accept both cases
const regex = /^#[0-9A-Fa-f]{6}$/;
4. Normalize Hex Colors
function normalizeHex(color) {
// Remove # and lowercase
let normalized = color.replace('#', '').toLowerCase();
// Expand shorthand
if (normalized.length === 3) {
normalized = normalized.split('').map(c => c + c).join('');
}
return '#' + normalized;
}
console.log(normalizeHex('#F53')); // #ff5533
console.log(normalizeHex('#FF5733')); // #ff5733
Common Pitfalls
Pitfall 1: Missing # Symbol
// BAD: Allows FF5733
^[0-9A-F]{6}$
// GOOD: Requires #
^#[0-9A-F]{6}$
Pitfall 2: Incorrect Lengths
// BAD: Allows #FF57
^#[0-9A-F]{5}$
// GOOD: Only 3 or 6 digits
^#([0-9A-F]{6}|[0-9A-F]{3})$
Pitfall 3: Case Sensitivity Issues
// BAD: Won't match lowercase
const regex = /^#[0-9A-F]{6}$/;
// GOOD: Matches both cases
const regex = /^#[0-9A-Fa-f]{6}$/i;
Testing Your Hex Color Validation
Use our interactive Regex Tester with these test cases:
Valid Hex Colors:
#FF5733(6-digit)#F53(3-digit shorthand)#ABCDEF(uppercase)#abcdef(lowercase)#AbCdEf(mixed case)#FF573380(with alpha)#F538(3-digit with alpha)
Invalid Hex Colors:
FF5733(missing #)#FF57(incorrect length)#GGGGGG(invalid hex characters)#FF57333(incorrect length)#FF573(incorrect length)
Real-World Examples
Extract from HTML/CSS Files
(#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3}|#[0-9A-Fa-f]{8}|#[0-9A-Fa-f]{4})
Finds: All hex color codes in web files
Find in Configuration Files
"(?:color|background|border-color)":\s*"(#(?:[0-9A-Fa-f]{6}|[0-9A-Fa-f]{3}))"
Finds: Color properties in JSON/YAML configs
Validate User Input
function validateUserColor(input) {
const hexRegex = /^#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{3})$/i;
if (hexRegex.test(input)) {
return { valid: true, color: input };
} else {
// Try to convert from other formats
if (input.startsWith('rgb(')) {
return { valid: true, color: rgbToHex(input) };
}
return { valid: false, error: 'Invalid color format' };
}
}
Conclusion
Hex color validation with regex is straightforward and reliable. The pattern ^#([0-9A-Fa-f]{6}|[0-9A-Fa-f]{3})$ provides comprehensive validation for standard hex color formats.
Remember to:
- Always include the # symbol
- Support both 3-digit and 6-digit formats
- Handle case sensitivity appropriately
- Consider alpha channel if needed
- Validate before processing user input
For complex color operations (conversions, manipulations), consider using specialized color libraries in combination with regex for validation.
Experiment with different patterns using our Regex Tester to find the perfect fit for your color validation needs!
About the Author
The Regex Master Team consists of experienced developers and technical writers dedicated to simplifying regular expressions for everyone. We ensure all patterns are rigorously tested and verified to provide accurate, production-ready solutions.
Try It: Regex Tester
Use our interactive regex tester to experiment with the patterns you learned in this article. Test your regular expressions in real-time and see immediate results.