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})$/iThe problem
Check that a string is a CSS hex colour, in either the short or the long form.
How it reads
Follow the line from left to right — every path you can trace is a string this pattern matches.
^#(?:[0-9a-f]{3}|[0-9…In order:^The start of the text (or of a line with the m flag)#The character "#"(?:[0-9a-f]{3}|[0-9a-…Group (not captured):[0-9a-f]{3}|[0-9a-f]{…Any one of these alternatives:[0-9a-f]{3}Any one of: "0" to "9" or "a" to "f", exactly 3 times, as many as possible[0-9a-f]{6}Any one of: "0" to "9" or "a" to "f", exactly 6 times, as many as possible$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.