Skip to content
shellhacks.dev
Regular Expressions

Match a hex color

Match a CSS hex color with #[0-9a-fA-F]{6}, add a three digit form with an alternation, and anchor it. Unanchored, #1234567 still matches its first six digits.

1 min read
Summarize in AI

A form field should accept #1a2b3c and #fff, and reject a longer string of hex digits.

Python
import re

loose = re.compile(r"#[0-9a-fA-F]{6}")
strict = re.compile(r"#(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{3})")
for s in ["#1a2b3c", "#FFF", "#12345", "#1234567", "1a2b3c", "#ggg111"]:
    print(f"{s:9} loose={bool(loose.fullmatch(s))} search={bool(loose.search(s))} strict={bool(strict.fullmatch(s))}")
Text
#1a2b3c   loose=True search=True strict=True
#FFF      loose=False search=False strict=True
#12345    loose=False search=False strict=False
#1234567  loose=False search=True strict=False
1a2b3c    loose=False search=False strict=False
#ggg111   loose=False search=False strict=False

The class [0-9a-fA-F] is one hex digit and {6} repeats it exactly six times. A search finds the first six digits of #1234567 and calls it a match, which is why validation needs fullmatch or ^...$ anchors, the point made in the re documentation. The non-capturing group in the strict pattern lists the two lengths CSS allows.

CSS also has the four and eight digit forms with an alpha channel, #rgba and #rrggbbaa, so extend the alternation if you accept them. In a pattern with the case-insensitive flag the class can be shortened to [0-9a-f]. A color name or an rgb() function is a different syntax and needs its own pattern.

Taggedregex
Share

More snippets

Regular Expressions

Match a quoted string

Match a quoted string with a negated character class. An escaped quote inside the text ends the match early, and a PCRE alternation that pairs backslashes handles it.

1 min read
Regular Expressions

Match a semantic version

Match a semantic version with the pattern from semver.org, which runs in grep -E. It rejects leading zeros, a bare 1.2 and a v prefix, and takes pre-release tags.

1 min read
Regular Expressions

Match a UUID

Match a version 4 UUID with 8-4-4-4-12 hex groups, a 4 at the start of the third group and 8, 9, a or b at the start of the fourth. Add -i for uppercase.

2 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.