Regex for Hex Color with Alpha
Regex Pattern
^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{3})$Hex color code with optional alpha channel (3, 4, 6, or 8 digits)
Quick Answer
The regex pattern for hex color with alpha is `^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{3})$`. Hex color code with optional alpha channel (3, 4, 6, or 8 digits). This works in JavaScript, Python, Ruby, PHP, Java, and most regex engines that support PCRE syntax.
Test Examples
| Input | Result |
|---|---|
| #FF5733FF | ✓ Matches |
| #FFF | ✓ Matches |
| #FFFF | ✓ Matches |
| #FF5733 | ✓ Matches |
| #FFFFF | ✗ No match |
| red | ✗ No match |
| #GGGGG | ✗ No match |
Code Examples
javascript
const regex = /^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{3})$/;
const isValid = regex.test(value);python
import re
pattern = r'^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{3})$'
if re.match(pattern, value):
print("valid")ruby
pattern = /^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{3})$/
if value =~ pattern
puts "valid"
endphp
if (preg_match('/^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{3})$/', $value)) {
echo "valid";
}java
String pattern = "^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{4}|[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
Hex Color Code
3 or 6-digit hex color with optional #
USD Currency
US dollar amount with optional $ and thousands separators
RGB Color
CSS RGB color function rgb(r, g, b)