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
| Input | Result |
|---|---|
| #fff | ✓matches |
| #00e5ff | ✓matches |
| #0a0d14ff | ✓matches |
| #ABC | ✓matches |
| #ff | ✗rejects |
| #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
- theme JSON validation
- Sketch/Figma export cleanup
- CSS audit for inline colors
- branding consistency check
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