Hex Color with Alpha Regex

^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{3})$

Match hex colors including 8-digit RGBA and 4-digit shorthand with alpha.

Test This Pattern →

Pattern Breakdown

Understanding the regex pattern ^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{3})$:

  • ^ - Start of string
  • $ - End of string
  • ? - Optional (zero or one)
  • [...] - Character class
  • (...) - Capturing group
  • {n,m} - Quantifier (n to m times)
  • | - Alternation (OR)

Examples

Input Result Explanation
#FF573380 ✓ Match 8-digit with alpha
#F538 ✓ Match 4-digit with alpha

Code Examples

JavaScript

JavaScript
const pattern = /^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{3})$/;
const text = "#FF573380";

// Test if string matches
if (pattern.test(text)) {
  console.log("Valid!");
}

// Extract matches
const matches = text.match(pattern);
console.log(matches);

Python

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})$'
text = "#FF573380"

# Test if string matches
if re.match(pattern, text):
    print("Valid!")

# Find all matches
matches = re.findall(pattern, text)
print(matches)

PHP

PHP
<?php
$pattern = '/^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{3})$/';
$text = "#FF573380";

// Test if string matches
if (preg_match($pattern, $text)) {
    echo "Valid!";
}

// Find all matches
preg_match_all($pattern, $text, $matches);
print_r($matches);
?>

Java

Java
import java.util.regex.*;

String pattern = "^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{3})$";
String text = "#FF573380";

Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(text);

if (m.matches()) {
    System.out.println("Valid!");
}

Use Cases

Common applications: Modern CSS, graphics applications

Frequently Asked Questions

What is the regex pattern for hex color with alpha regex?
The regex pattern is: ^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{3})$. Match hex colors including 8-digit RGBA and 4-digit shorthand with alpha.
How do I use the hex color with alpha regex pattern in JavaScript?
In JavaScript: const regex = new RegExp('^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{3})$'); or const regex = /^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{3})$/;
Does this pattern work in Python?
Yes, use: import re; pattern = re.compile(r'^#?([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{4}|[A-Fa-f0-9]{3})$') in Python. Most regex patterns are cross-language compatible.
What are common use cases for hex color with alpha regex?
Modern CSS, graphics applications

Related Regex Patterns

More Regex Tools

GetDevUtils offers a suite of developer tools including: