tools / regex library / hex color
regex pattern · ready to copy

Regex for matching hex colors

Match #RGB, #RRGGBB, and #RRGGBBAA (with alpha).

intermediate javascript / pcre / python4 use cases

The pattern

#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})\b

Test cases

InputResult
#fffmatches
#00e5ffmatches
#0a0d14ffmatches
#ABCmatches
#ffrejects
#ggg (not hex)rejects
rgb(0,0,0)rejects

Edge cases & caveats

CSS named colors (`red`, `blue`) and `rgb()`/`hsl()`/`oklch()` don't match. Add `\b` so `#abc` followed by `def` doesn't accidentally match `#abcdef` if undesired.

Common use cases

Try variations against your data
regexlab is a free in-browser tester with side-by-side match highlighting, group inspector, and named-capture export to JS/Python/PCRE.
Open regexlab  

Related

sql injection keywords · phone number · username · bitcoin address