Regex for Matching a Hex Color Code

Matches 3-digit or 6-digit hex color codes prefixed with #.

Published October 10, 2026

This regex matches CSS hex colours with 3 or 6 hexadecimal digits, with an optional leading #.

How the pattern works

Breaking the pattern down: #? = optional hash; [0-9a-fA-F]{3} = short form like #fff; {6} = long form like #ffffff.

Test your regex against both matching and non-matching inputs; use the Regex tool on this site to experiment live.

Pattern tests

/^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/
✓ '#fff'
✓ '#1a2B3c'
✓ 'abc123'
✗ '#ffff'
✗ '#gggggg'

Practical examples

The pattern

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

Test it

const re = /^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/
re.test('#fff')   // true
re.test('#1a2B3c')   // true
re.test('#ffff')   // false
re.test('#gggggg')   // false

In Python

import re
re.search(r'^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$', text)

Common mistakes

  • Forgetting 8-digit RGBA hex (#rrggbbaa).
  • Case sensitivity mistakes.
  • Allowing 4 or 5 digits accidentally.

Key takeaways

  • Anchors (^ and $) make the whole string match instead of a part of it.
  • Regex checks format only; verify data separately when it matters.
  • Test with valid and invalid samples.

FAQ

Support alpha?

Add |[0-9a-fA-F]{8} and {4} variants.

Where can I test this pattern?

Use the Regex Tester on this site, or regex101.com.

More General articles