Regex for Hex Color Code
Regex Pattern
^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$3 or 6-digit hex color with optional #
Quick Answer
The regex pattern for hex color code is `^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$`. 3 or 6-digit hex color with optional #. This works in JavaScript, Python, Ruby, PHP, Java, and most regex engines that support PCRE syntax.
Test Examples
| Input | Result |
|---|---|
| #FFF | ✓ Matches |
| #ffffff | ✓ Matches |
| FF5733 | ✓ Matches |
| #a1b2c3 | ✓ Matches |
| #FFFF | ✗ No match |
| red | ✗ No match |
| #GGGGGG | ✗ No match |
Code Examples
javascript
const regex = /^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/;
const isValid = regex.test(value);python
import re
pattern = r'^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$'
if re.match(pattern, value):
print("valid")ruby
pattern = /^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/
if value =~ pattern
puts "valid"
endphp
if (preg_match('/^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/', $value)) {
echo "valid";
}java
String pattern = "^#?([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$";
boolean isValid = value.matches(pattern);Frequently Asked Questions
Related Regex Patterns
Positive Integer
Integers greater than zero (no leading zeros)
Non-negative Integer
Zero or positive integer
Decimal Number
Optionally signed decimal number
USD Currency
US dollar amount with optional $ and thousands separators
Email Address
Validates a standard email address format
Email (RFC 5322 Compliant)
RFC 5322 compliant email validation with label length limits