Skip to content

Regex for Hex Color — Pattern, Examples & Caveats

Pattern
^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$

This pattern validates CSS hexadecimal color codes with an optional leading #, accepting the 3, 4, 6 and 8 digit forms that correspond to RGB, RGBA, RRGGBB and RRGGBBAA notations. Web patterns deal with markup, styling and web identifiers: HTML tags and comments, CSS colors, Markdown links, slugs and source-code comments. They are handy for quick scanning and lightweight transforms, but markup is not a regular language, so anything structural or security-sensitive should use a real parser (DOM, CSS or Markdown) rather than regex alone. It needs no special flags. Apply it to the whole input as a format contract. It accepts colors without the # because of #?; require the hash by removing the ? if your context needs it. It does not validate other CSS color syntaxes like rgb(), hsl() or named colors — those need separate patterns or a CSS parser. The 4 and 8 digit alpha forms are modern CSS Color 4; very old browsers may not render them. As with any regular expression, confirm its behavior in your target engine, test boundary and adversarial inputs, and watch for catastrophic backtracking before relying on it in production.

Advertisement
Ad slot · ref-top

Token-by-token explanation

  • ^ — start anchor
  • #? — optional literal hash
  • [0-9a-fA-F]{3} — shorthand RGB (e.g. #fff)
  • [0-9a-fA-F]{4} — shorthand RGBA with alpha
  • [0-9a-fA-F]{6} — full RRGGBB
  • [0-9a-fA-F]{8} — full RRGGBBAA with alpha
  • $ — end anchor

What it matches

#fff#1a2b3c#FF00001a2b3c4d#abcd

What it does not match

#gg0000#12345#12rgb(0,0,0)#1234567

When to use it

Reach for a web pattern for quick scanning and lightweight transforms of markup, styling and web identifiers: locating tags, comments, colors, slugs or Markdown links. For anything structural or security-sensitive — parsing a DOM, sanitizing HTML, rewriting CSS — use a real parser or a proven library instead, because markup is not a regular language and regex-based handling is a frequent source of bugs and cross-site scripting bypasses.

Caveats

  • It accepts colors without the # because of #?; require the hash by removing the ? if your context needs it.
  • It does not validate other CSS color syntaxes like rgb(), hsl() or named colors — those need separate patterns or a CSS parser.
  • The 4 and 8 digit alpha forms are modern CSS Color 4; very old browsers may not render them.

Code examples

JavaScript
const re = /^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
const input = "#fff";
if (re.test(input)) {
  // valid: proceed
} else {
  // reject with a helpful message
}
Python
import re

rx = re.compile(r"^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$")
value = "#fff"
if rx.fullmatch(value):
    pass  # valid
else:
    raise ValueError("invalid format")
Java
import java.util.regex.*;

Pattern p = Pattern.compile("^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$");
Matcher m = p.matcher("#fff");
boolean ok = m.matches();   // whole input must conform
PHP
<?php
$subject = "#fff";
if (preg_match('/^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/', $subject, $m)) {
    // $m[0] is the full match
}

How to test it

Before trusting any pattern, test it against three kinds of input: valid examples that must match, invalid examples that must be rejected, and edge cases at the boundaries (empty strings, maximum lengths, unusual separators and Unicode). Paste the expression into a live regex tester with your actual sample data and confirm the highlighted matches are exactly what you intend. Watch for catastrophic backtracking by trying long non-matching inputs, and remember that engine differences (JavaScript, Python, Java, PCRE, Go/RE2) mean a pattern that works in one may fail or behave differently in another — especially lookarounds, which Go's RE2 does not support at all.

Frequently asked questions

What is the difference between #fff and #ffffff?

They are the same color: the 3-digit shorthand expands each digit by doubling it, so #fff equals #ffffff. The regex accepts both forms.

Does it support alpha transparency?

Yes — the 4-digit (#rgba) and 8-digit (#rrggbbaa) forms include an alpha channel, where the last digit(s) encode opacity from 00 (transparent) to ff (opaque).

When should I avoid regex for web content?

For parsing HTML, CSS or Markdown structure, use a real parser. Regex cannot handle nesting, quoted delimiters or malformed markup reliably, and regex-based sanitization is a common source of XSS bypasses.

Why is regex HTML sanitization dangerous?

HTML has nested, quoted and malformed constructs that regex mis-parses, so attackers hide scripts in forms the pattern misses. Always sanitize with a proven library (DOMPurify) or a real parser, never ad-hoc regex.

Advertisement
Ad slot · ref-in-article

Try the Regex Tester

Live regex matching with groups, flags and explanations.

Open tool →