Regular Expressions 101

Community Patterns

Your search did not match anything

Community Library Entry

1

Regular Expression
Python

r"
^#([0-9a-f]{3}){1,2}$
"
gmi

Description

Verifies whether each input line contains a valid three- or six-digit hexadecimal number, commonly used as color codes in CSS and other technologies. Each number must begin with the "#" sign.

I've seen other regexes for this which use individual expressions for a three-digit number and a six-digit number as alternates for each other. I didn't see any reason to repeat the character class twice, so I used only one pattern of three digits, which may appear one or two times.

Valid Hex Color Codes

#FFF
#025
#F0A1FB

Invalid Hex Color Codes

#fffabg
#abcf
#12365erff
Submitted by Mr. Lance E Sloan - 14 days ago