Match hex color codes in both 3-digit (#fff) and 6-digit (#ffffff) formats. Perfect for CSS color extraction and validation.
/#(?:[0-9a-fA-F]{3}){1,2}\b/g| Token | Meaning |
|---|---|
# | Literal hash symbol prefix |
[0-9a-fA-F]{3} | Exactly 3 hexadecimal characters (0-9, a-f, A-F) |
{1,2} | Repeat 1 or 2 times (matches #fff or #ffffff) |
\b | Word boundary to prevent partial matches |
#fffMatch#000000Match#1a2B3cMatch#F00Match#ggggggNo matchfffNo matchconst hexColorRegex = /#(?:[0-9a-fA-F]{3}){1,2}\b/g;
const css = "body { color: #333; background: #f0f0f0; border: 1px solid #1a2B3c; }";
const matches = css.match(hexColorRegex);
console.log(matches); // ["#333", "#f0f0f0", "#1a2B3c"]import re
hex_color_regex = r'#(?:[0-9a-fA-F]{3}){1,2}\b'
css = "body { color: #333; background: #f0f0f0; border: 1px solid #1a2B3c; }"
matches = re.findall(hex_color_regex, css)
print(matches) # ['#333', '#f0f0f0', '#1a2B3c']Want to test this pattern with your own data?
Try this pattern in Regex Tester →