breakitdown

Regex for a hex color code

Answer

^#(?:[0-9a-f]{3}|[0-9a-f]{6})$ with the i flag matches #fff and #ffffff in any case. To also accept alpha (#rgba, #rrggbbaa), use ^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$.

flags: g all matches · i ignore case · m ^ $ per line · s . matches newlines · u Unicode

JavaScript ✓PCRE ✓

No catastrophic-backtracking patterns found. (A heuristic check: nested and adjacent repeats, overlapping alternatives.)

  1. ^Start of the stringanchor
  2. #The character '#' literally (any case, because of the i flag)literal
  3. (?:…)Non-capturing group: groups without rememberinggroup
  4. |Either of 2 alternatives, tried left to right; the first that leads to an overall match winsalternation
  5. Alternative 1:
  6. [0-9a-f]One character: 0-9 (digits) or a-f (either case, because of the i flag)character class
  7. {3}Repeat the class exactly 3 timesquantifier
  8. Alternative 2:
  9. [0-9a-f]One character: 0-9 (digits) or a-f (either case, because of the i flag)character class
  10. {6}Repeat the class exactly 6 timesquantifier
  11. $End of the stringanchor

Examples

Checked at build time in JavaScript and in Python's re.

InputMatches?
#fff✓ match
#FFFFFF✓ match
#1a2B3c✓ match
#ffff✗ no match
#12345✗ no match
fff✗ no match
#ggg✗ no match
#ff000080✗ no match
# fff✗ no match

Try your own text

One string per line: each line is tested on its own (the m flag is added here).

How it works

A hex color is a # and then 3, 4, 6 or 8 hexadecimal digits. The 3-digit form is shorthand: each digit is doubled, so #f0a means #ff00aa. The 4- and 8-digit forms add an alpha channel and come from CSS Color Module Level 4. Every current browser supports them.

Writing [0-9a-f]{3}|[0-9a-f]{6} instead of [0-9a-f]{3,6} matters. The range version accepts 4 and 5 digits, and 5 is never valid.

Variants

Gotchas

Related explainers

← Explain any regular expression