DD
DevDash

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

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

php

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

Want API access + no ads? Pro coming soon.