Skip to content
Regex for Hex Color Codes — Pattern Explained with Examples

Regex for Hex Color Codes — Pattern Explained with Examples

DodaTech Updated Jun 20, 2026 3 min read

This regex validates hexadecimal color codes used in web design and graphics. It supports both the 6-digit (#RRGGBB) and 3-digit shorthand (#RGB) formats, with the # prefix being optional. This is one of the most commonly used patterns in front-end development for CSS color validation, color picker tools, and design system utilities.

The Pattern

/^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/

Pattern Breakdown

PartMeaning
^Start of string
#?Optional hash/pound sign prefix
(Start of alternation group
[0-9a-fA-F]{3}Exactly 3 hex digits (shorthand: e.g., F00 = #FF0000)
|OR
[0-9a-fA-F]{6}Exactly 6 hex digits (full: e.g., FF5733)
)End of alternation group
$End of string

Matches

  • #FF5733
  • #abc
  • 123456
  • #000
  • #FFFFFF
  • #f0f0f0
  • ABC123

Does NOT Match

  • #FF573 — 5 hex digits after #
  • #GGGGGG — G is not a valid hex character
  • #1234 — 4 hex digits after #
  • #ABCDE — 5 hex digits after #
  • ##FF5733 — double hash
  • rgb(255,87,51) — RGB function, not hex
  • transparent — named color, not a hex code
  • #FFF (with trailing space) — trailing whitespace violates end anchor

Language Examples

JavaScript

const hexRegex = /^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;

console.log(hexRegex.test('#FF5733'));  // true
console.log(hexRegex.test('#abc'));     // true
console.log(hexRegex.test('#GGGGGG'));  // false

// Convert 3-digit to 6-digit
function expandHex(hex) {
  const cleaned = hex.replace('#', '');
  if (cleaned.length === 3) {
    return cleaned[0] + cleaned[0] + cleaned[1] + cleaned[1] + cleaned[2] + cleaned[2];
  }
  return cleaned;
}
console.log(expandHex('#abc'));  // aabbcc

Python

import re

hex_regex = r'^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$'

print(bool(re.match(hex_regex, '#FF5733')))  # True
print(bool(re.match(hex_regex, '#abc')))     # True
print(bool(re.match(hex_regex, '#GGGGGG')))  # False

# Convert 3-digit to 6-digit
def expand_hex(hex_code):
    cleaned = hex_code.lstrip('#')
    if len(cleaned) == 3:
        return ''.join(c * 2 for c in cleaned)
    return cleaned

print(expand_hex('#abc'))  # aabbcc

Common Pitfalls

  1. 3-digit shorthand expansion#F00 is shorthand for #FF0000. Each hex digit doubles: #RGB#RRGGBB. When processing, ensure you expand shorthand before converting to RGB values.

  2. Case insensitivity — Both uppercase (#FF5733) and lowercase (#ff5733) are valid. The pattern uses [0-9a-fA-F] for case-insensitive matching, but you may need to normalize case before comparison.

  3. Optional # prefix — CSS requires the #, but some color pickers and APIs accept raw hex values. The #? makes it optional. For CSS validation, remove the ? to enforce the hash.

  4. Alpha channel not supported — CSS Color Level 4 introduces 8-digit hex (#RRGGBBAA) for RGBA colors. To support it, extend the alternation: [0-9a-fA-F]{8}.

Real-World Use Cases

  • Form validation — Accepting user-entered hex color codes in theme customizers
  • Color picker tools — Validating user input alongside a visual color picker interface
  • Design system utilities — Parsing and converting hex colors to RGB, HSL, or CSS variables

FAQ

Extend the alternation to include {8}: /^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/. The 8-digit format uses the last two hex digits for the alpha channel (00–FF, where FF is fully opaque).
No. CSS named colors (over 140, including rebeccapurple) are not hex codes and are not matched by this regex. For full CSS color validation, check named colors separately or use a CSS color parser library.

Related Patterns

Previous Regex for Social Security Number — Pattern Explained with Examples Next Regex for Password Strength — Pattern Explained with Examples

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro

Home Browse Regex Pattern Library