Regex for Hex Color Code
This regex matches hexadecimal color codes in 3-digit, 6-digit, and 8-digit formats with an optional # prefix. The 3-digit shorthand (#FFF) expands to 6 digits (#FFFFFF), and the 8-digit format includes an alpha channel for transparency. Hex colors are the most common way to specify colors in CSS, HTML, and design tools.
^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$ What is the regex pattern for Hex Color Code?
The regex pattern for Hex Color Code is ^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$ with the i flag. This regex matches hexadecimal color codes in 3-digit, 6-digit, and 8-digit formats with an optional # prefix. The 3-digit shorthand (#FFF) expands to 6 digits (#FFFFFF), and the 8-digit format includes an alpha channel for transparency. Hex colors are the most common way to specify colors in CSS, HTML, and design tools. This pattern is commonly used for css color validation and color picker inputs.
Test Examples
#FF5733 #FF5733 #fff #fff #FF573380 #FF573380 Common Uses
- ✓ CSS color validation
- ✓ Color picker inputs
- ✓ Design tool integration
- ✓ Theme configuration
Variations
6-digit only
^#[0-9a-fA-F]{6}$ Strict 6-digit with required hash
With alpha required
^#[0-9a-fA-F]{8}$ 8-digit format with alpha channel
CSS color extraction
#[0-9a-fA-F]{3,8} Find hex colors within CSS text
Frequently Asked Questions
What is the difference between 3-digit and 6-digit hex colors?
A 3-digit hex color like #F0A is shorthand for #FF00AA. Each digit is doubled to create the full 6-digit form. The 3-digit format is more concise but can only represent 4,096 colors compared to the 16.7 million of the 6-digit format.
What does the 8-digit hex format represent?
The 8-digit format (#RRGGBBAA) adds two digits for alpha (transparency). 00 is fully transparent and FF is fully opaque. This format is supported in CSS with the CSS Color Level 4 specification.
Should hex colors include the # symbol?
In CSS, the # is required. In many programming contexts and APIs, it is optional. This regex makes it optional to accommodate both use cases.