Hex Color Code
Match CSS hex color codes in both 3-digit (#RGB) and 6-digit (#RRGGBB) formats.
Try it in RegexPro →Available in
JavaScript / ECMAScript code
const re = new RegExp("#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{3})\\b", "g");
const input = "#ff5733";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
Python (re) code
import re
pattern = re.compile(r"#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{3})\b")
input_text = "#ff5733"
for m in pattern.finditer(input_text):
print(m.group(0))Stdlib `re` module — no third-party dependency. Works on Python 3.6+.
Go (RE2) code
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{3})\b`)
input := `#ff5733`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
Pattern
#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{3})\b (flags: g)Raw source: #(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{3})\b
How it works
Examples
Input
#ff5733Matches
#ff5733
Input
#abcMatches
#abc
Input
#FFFFFFMatches
#FFFFFF
Common use cases
- •CSS/SCSS color extraction
- •Design token parsing
- •Theme file analysis
- •Color palette generators
Related patterns
CSS rgb() Color
WebMatch CSS rgb() and rgba() color functions, including an optional alpha channel.
CSS hsl() / hsla() Color
WebMatch CSS hsl() and hsla() color functions, capturing hue (0–360), saturation, lightness, and optional alpha.
HTML5 Color Input Value
WebValidate the value of an HTML5 `<input type="color">` — exactly 6 hex digits with leading hash.
CSS Custom Property (Variable)
WebMatch CSS custom properties (variables) like `--brand-color` or `--font-size-lg`.
Related concepts
Word Boundaries: \b and \B
Concept\b matches the position between a word character and a non-word character. It keeps your regex from matching 'cat' inside 'concatenate.'
Custom Character Sets: [abc], [a-z], [^abc]
ConceptSquare brackets build a custom character class. [abc] matches any of a, b, or c. [a-z] is a range. A leading ^ negates the set.
How to Escape Regex Special Characters
How-toBackslash-escape any of .^$*+?()[]{}|\ to match them literally. When building a regex from user input, use a full-escape helper function.