Last active
December 9, 2023 12:52
-
-
Save olmokramer/82ccce673f86db7cda5e to your computer and use it in GitHub Desktop.
Regex for CSS colors: hex, rgb(a), hsl(a)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/(#([0-9a-f]{3}){1,2}|(rgba|hsla)\(\d{1,3}%?(,\s?\d{1,3}%?){2},\s?(1|0?\.\d+)\)|(rgb|hsl)\(\d{1,3}%?(,\s?\d{1,3}%?\)){2})/i |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's the regular expression I've got. It recognizes hex-colors and simple color functions. I'm using it in a
remarkjs
plugin to add color squares next to colors, similar to how GitHub does this:#4F82A9
. It might be a bit too big, but it runs on the server for me, so it's fine.And I'm constructing it like this (JavaScript):
Here's what this regex doesn't recognize:
lab()
,lch()
,oklab()
,oklch()
,color()
,none
keyword,<system-color>
type,transparent
,currentColor
and named colors. Feel free to extend on this one, I'm not planning to, since for my use case I don't need that much specificity.