Regex for Hex Color Code
Matches hex color codes in 3-digit (#FFF), 6-digit (#FF00FF), and 8-digit (#FF00FF80, with alpha) formats.
Pattern
/^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/Pattern Breakdown
| Token | Explanation |
|---|---|
| ^ | Start of string |
| #? | Optional hash symbol |
| [0-9a-fA-F]{3} | 3-digit shorthand (e.g., FFF) |
| [0-9a-fA-F]{6} | 6-digit full color (e.g., FF00FF) |
| [0-9a-fA-F]{8} | 8-digit with alpha (e.g., FF00FF80) |
| $ | End of string |
Test Examples
| Input | Match? |
|---|---|
| #FF5733 | Match |
| #fff | Match |
| 00FF00 | Match |
| #GG0000 | No match |
| #FFFFF | No match |
Common Use Cases
- CSS color validation
- Design tool input
- Theme configuration
Variations
^#[0-9a-fA-F]{6}$6-digit with required hash only
Other Regex Patterns
Want to test this pattern with your own data?
Open the Regex Tester