Regex for CSS Color Value
Matches CSS color values including hex (#RGB, #RRGGBB, #RRGGBBAA), rgb(), rgba(), hsl(), and hsla() functions.
Pattern
/^(#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})|rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}(\s*,\s*(0|1|0?\.\d+))?\s*\)|hsla?\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%(\s*,\s*(0|1|0?\.\d+))?\s*\))$/i Live Tester
Enter a string to test
Examples
The i flag makes the pattern case-insensitive.
✓ #ff5733
✓ rgb(255, 128, 0)
✓ hsla(120, 100%, 50%, 0.5)
✗ red
✗ rgb(256)
✗ #gggggg
Pattern Breakdown
#([0-9a-fA-F]{3}|{6}|{8}) — hex color with 3, 6, or 8 digits
rgba?\(\d{1,3},\d{1,3},\d{1,3}(,alpha)?\) — rgb/rgba function
hsla?\(\d{1,3},\d{1,3}%,\d{1,3}%(,alpha)?\) — hsl/hsla function
Code Snippets
Javascript
const regex = /^(#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})|rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}(\s*,\s*(0|1|0?\.\d+))?\s*\)|hsla?\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%(\s*,\s*(0|1|0?\.\d+))?\s*\))$/i;
regex.test("rgb(255, 128, 0)"); // true Python
import re
pattern = r"^(#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})|rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}(\s*,\s*(0|1|0?\.\d+))?\s*\)|hsla?\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%(\s*,\s*(0|1|0?\.\d+))?\s*\))$"
bool(re.match(pattern, "rgb(255, 128, 0)", re.I)) # True Php
$pattern = '/^(#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})|rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}(\s*,\s*(0|1|0?\.\d+))?\s*\)|hsla?\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%(\s*,\s*(0|1|0?\.\d+))?\s*\))$/i';
preg_match($pattern, "rgb(255, 128, 0)"); // 1 Related Patterns
Email Address /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/ URL /^https?:\/\/(www\.)?[a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([a-zA-Z0-9()@:%_+.~#?&/=-]*)$/ Phone Number (International) /^\+?[1-9]\d{1,14}$/ Phone Number (US) /^\(?[2-9]\d{2}\)?[-.\s]?\d{3}[-.\s]?\d{4}$/ Phone Number (EU) /^\+?[1-9][0-9]{0,3}[\s.-]?\(?[0-9]{1,5}\)?[\s.-]?[0-9]{1,5}[\s.-]?[0-9]{1,5}$/ IPv4 Address /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/
Frequently Asked Questions
What is the regex for CSS Color Value?▾
The regex pattern for CSS Color Value is /^(#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})|rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}(\s*,\s*(0|1|0?\.\d+))?\s*\)|hsla?\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%(\s*,\s*(0|1|0?\.\d+))?\s*\))$/i. Matches CSS color values including hex (#RGB, #RRGGBB, #RRGGBBAA), rgb(), rgba(), hsl(), and hsla() functions.
How do I use the CSS Color Value regex in JavaScript?▾
In JavaScript you create the pattern with a regex literal or the RegExp constructor and call .test() to check a string against it. A ready-to-copy example is shown in the Code Snippets section above, alongside Python and PHP versions.
What does the CSS Color Value pattern match?▾
It matches strings like #ff5733; it rejects strings like red. See the Examples section above for the full list of matching and non-matching cases.