Hex color regex
Regex to match CSS hex colours: #RGB, #RGBA, #RRGGBB and #RRGGBBAA. Tested examples.
Pattern
/^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/Matches
#fff#1d1a22#FF000080
Doesn't match
fff#ff#12345#ggg
Notes
- Lengths 3, 4, 6 and 8 are valid in CSS Color Level 4; 5 and 7 are not.
- Drop the ^ and $ and add g to find every colour in a stylesheet.
Code
JavaScript
const re = /^#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
re.test(value); // true or falsePython
import re
bool(re.fullmatch(r'#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})', value))Try it on your own input
The live tester adds the g and m flags so every line is checked separately.
Questions
How do I make the # optional?
Change ^# to ^#?.
More patterns
Email regexPhone number regexURL regexIP address regexDate regexTime regex (24-hour and 12-hour)UUID regexPassword regex