Regex for a hex color code
^#(?:[0-9a-f]{3}|[0-9a-f]{6})$ with the i flag matches #fff and #ffffff in any case. To also accept alpha (#rgba, #rrggbbaa), use ^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$.
JavaScript ✓PCRE ✓
No catastrophic-backtracking patterns found. (A heuristic check: nested and adjacent repeats, overlapping alternatives.)
^Start of the stringanchor#The character '#' literally (any case, because of the i flag)literal(?:…)Non-capturing group: groups without rememberinggroup|Either of 2 alternatives, tried left to right; the first that leads to an overall match winsalternation- Alternative 1:
[0-9a-f]One character: 0-9 (digits) or a-f (either case, because of the i flag)character class{3}Repeat the class exactly 3 timesquantifier- Alternative 2:
[0-9a-f]One character: 0-9 (digits) or a-f (either case, because of the i flag)character class{6}Repeat the class exactly 6 timesquantifier$End of the stringanchor
Examples
Checked at build time in JavaScript and in Python's re.
| Input | Matches? |
|---|---|
#fff | ✓ match |
#FFFFFF | ✓ match |
#1a2B3c | ✓ match |
#ffff | ✗ no match |
#12345 | ✗ no match |
fff | ✗ no match |
#ggg | ✗ no match |
#ff000080 | ✗ no match |
# fff | ✗ no match |
Try your own text
One string per line: each line is tested on its own (the m flag is added here).
How it works
A hex color is a # and then 3, 4, 6 or 8 hexadecimal digits. The 3-digit form is shorthand: each digit is doubled, so #f0a means #ff00aa. The 4- and 8-digit forms add an alpha channel and come from CSS Color Module Level 4. Every current browser supports them.
Writing [0-9a-f]{3}|[0-9a-f]{6} instead of [0-9a-f]{3,6} matters. The range version accepts 4 and 5 digits, and 5 is never valid.
Variants
/^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/iAlso accepts the alpha forms#rgbaand#rrggbbaa./#(?:[0-9a-f]{6}|[0-9a-f]{3})\b/giFind colors inside a stylesheet. The 6-digit branch comes first so#ffffffis not cut short to#fff.
Gotchas
- Without the
iflag, uppercase digits like#FFFfail. Hex is case-insensitive in CSS. - The main pattern rejects
#ff000080, which is valid CSS for 50% transparent red. Use the alpha variant for anything that accepts modern CSS. - A missing
#fails. Color pickers and design tools often copy the value without it, so you may want^#?and add the#yourself. - Named colors (
red) and functions (rgb(255 0 0)) are valid CSS colors too. To accept anything a browser accepts, assign the value to an element'sstyle.colorand check whether it stuck, or useCSS.supports("color", s).
Related explainers
- Regex for a UUIDRegexes for UUIDs in the standard 8-4-4-4-12 form: any version, version 4 only, and versions 1-8 with the...
- Regex for a URL slugA regex that validates URL slugs like my-first-post: lowercase letters and digits joined by single...
- Regex for digits only, integers and decimalsRegexes for digits only, signed integers and decimal numbers, with the edge cases: leading zeros, a bare...