HomeRegex LibraryHexadecimal Color Code (#HEX) Regex
100% Client-Side β€’ 0 B Data Leaves Browser
formatting

Hexadecimal Color Code (#HEX) Regex

Matches 3-digit shorthand, 6-digit RGB, or 8-digit RGBA hex color codes.

Regular Expression Pattern:
/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/
Valid Match Example:
#10b981
Invalid / Non-Match Example:
#10b981999

Regex Syntax Breakdown & Explanation

  • β€’^# : Requires hashtag prefix
  • β€’[0-9a-fA-F]{3} : 3-digit shorthand (#RGB)
  • β€’[0-9a-fA-F]{6} : 6-digit standard (#RRGGBB)
  • β€’[0-9a-fA-F]{8} : 8-digit alpha (#RRGGBBAA)

Implementation in Popular Languages

JavaScript / TypeScript
const regex = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
const isValid = regex.test("#10b981");
console.log(isValid); // true
Python (re)
import re

pattern = r"^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$"
match = re.match(pattern, "#10b981")
print(bool(match)) # True
Go (regexp)
package main
import (
  "fmt"
  "regexp"
)

func main() {
  re := regexp.MustCompile(`^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$`)
  fmt.Println(re.MatchString("#10b981"))
}
Frequently Asked Questions

Frequently Asked Questions

Everything you need to know regarding specifications, syntax, and security best practices.

The regular expression pattern is /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/. Matches 3-digit shorthand, 6-digit RGB, or 8-digit RGBA hex color codes.