Regex patterns/Validation

Hex colour code

Three or six hex digits after a hash — and why the six-digit branch must come first.

/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i
Open it in Rex

The problem

Check that a string is a CSS hex colour, in either the short or the long form.

How it reads

start#group[0-9a-f]repeat[0-9a-f]repeatend

Follow the line from left to right — every path you can trace is a string this pattern matches.

  1. ^#(?:[0-9a-f]{3}|[0-9…In order:
  2. ^The start of the text (or of a line with the m flag)
  3. #The character "#"
  4. (?:[0-9a-f]{3}|[0-9a-…Group (not captured):
  5. [0-9a-f]{3}|[0-9a-f]{…Any one of these alternatives:
  6. [0-9a-f]{3}Any one of: "0" to "9" or "a" to "f", exactly 3 times, as many as possible
  7. [0-9a-f]{6}Any one of: "0" to "9" or "a" to "f", exactly 6 times, as many as possible
  8. $The end of the text (or of a line with the m flag)

Matches

  • #fff
  • #1a2b3c
  • #ABC
  • #000000

Does not match

  • #12345
  • rebeccapurple
  • #gggggg
  • fff

Where it bites

  • Order matters inside the alternation only when the pattern is unanchored. With ^ and $ here, #abcdef cannot sneak through as the three-digit branch — remove the anchors and it can.
  • Eight-digit colours with alpha (#rrggbbaa) are rejected; add {8} as another branch if you need them.
  • Case-insensitivity comes from the i flag, not from listing A-F.

More validation patterns