DD
DevDash

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

InputResult
#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"
end

php

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

Want API access + no ads? Pro coming soon.