DevTools
Back to Regex Tester

Hex Color Code Regex Pattern

Match hex color codes in both 3-digit (#fff) and 6-digit (#ffffff) formats. Perfect for CSS color extraction and validation.

The Pattern

/#(?:[0-9a-fA-F]{3}){1,2}\b/g

How It Works

TokenMeaning
#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)
\bWord boundary to prevent partial matches

Test Cases

#fffMatch
#000000Match
#1a2B3cMatch
#F00Match
#ggggggNo match
fffNo match

Code Examples

javascript
const 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"]
python
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']

Common Use Cases

Related Patterns

Want to test this pattern with your own data?

Try this pattern in Regex Tester →