🔍Regex Recipes

Hex Color Code

Match hexadecimal color codes in both 3-digit and 6-digit formats.

Pattern

^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$

Explanation

Validates hex color codes with optional # prefix. Accepts both shorthand (#RGB) and full (#RRGGBB) formats.

Examples

Full format
Input
#FF5733
Output
✓ Match
Shorthand
Input
#F57
Output
✓ Match
Without hash
Input
FF5733
Output
✓ Match
Lowercase
Input
#ff5733
Output
✓ Match
Invalid - wrong length
Input
#FF57
Output
✗ No match

Code Examples

JavaScript
const hexColorRegex = /^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
const isValidColor = hexColorRegex.test('#FF5733'); // true
CSS Usage
/* Both formats are valid in CSS */
.element {
  color: #F57;        /* Shorthand */
  background: #FF5733; /* Full format */
}

Try it Now

💡 Tips

  • Shorthand expands: #F57 becomes #FF5577
  • Case-insensitive - both uppercase and lowercase work
  • Add ^ and $ anchors to match entire string only