Hex Color Code
Match hex color codes in 3-digit or 6-digit format with optional # prefix.
What Is This?
This regex pattern matches hexadecimal color codes in both 3-digit shorthand (#fff) and 6-digit full (#ffffff) formats. The # prefix is optional. Hex color codes represent RGB values using hexadecimal notation: RRGGBB where each pair ranges from 00 to FF.
How to Use This Pattern
Pattern
^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$
^#?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$Usage
Use this pattern to validate color input in design tools, CSS editors, and configuration files. The pattern accepts both formats: #fff (shorthand where each digit is doubled to #ffffff) and #ffffff (full specification). The case-insensitive flag i allows both uppercase and lowercase hex digits.
Flags
Use the i flag for case-insensitive matching.
Examples
Matches: #ff0000, #00ff00, #0000ff, #FFFFFF, ff0000. Non-matches: #ffff, #gggggg, #12345, red
Matches: #fff, #abc, #123456, #AABBCC, f0f0f0. Non-matches: #abcd, #1234567, rgb(255,0,0), hsl(0,100%,50%)
Frequently Asked Questions
Should I include the # prefix in storage?
Consistency matters. If storing with #, always include it. If storing without, always exclude it. Most CSS color values use the # prefix, but some systems store the raw hex value for flexibility.
Does this pattern match 8-digit hex with alpha?
No. This pattern only matches 3-digit and 6-digit hex colors. For 8-digit hex (RRGGBBAA) with alpha channel, use: ^#?([0-9A-Fa-f]{4}|[0-9A-Fa-f]{8})$.