Skip to content

Instantly share code, notes, and snippets.

@olmokramer
Last active December 19, 2024 11:23
Show Gist options
  • Save olmokramer/82ccce673f86db7cda5e to your computer and use it in GitHub Desktop.
Save olmokramer/82ccce673f86db7cda5e to your computer and use it in GitHub Desktop.
Regex for CSS colors: hex, rgb(a), hsl(a)
/(#([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
@Chasmical
Copy link

Chasmical commented Dec 9, 2023

Here's the regular expression I've got. It recognizes hex-colors and a few 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.

/^(#(?:[0-9a-fA-F]{3}){1,2}|#(?:[0-9a-fA-F]{4}){1,2}|rgba?\(\s*\d*(?:\.\d*)?\s*,\s*\d*(?:\.\d*)?\s*,\s*\d*(?:\.\d*)?\s*(?:,\s*\d*(?:\.\d*)?%?\s*)?\)|rgba?\(\s*(?:\d*(?:\.\d*)?%|0)\s*,\s*(?:\d*(?:\.\d*)?%|0)\s*,\s*(?:\d*(?:\.\d*)?%|0)\s*(?:,\s*\d*(?:\.\d*)?%?\s*)?\)|rgba?\(\s*\d*(?:\.\d*)?%?\s+\d*(?:\.\d*)?%?\s+\d*(?:\.\d*)?%?\s*(?:\/\s*\d*(?:\.\d*)?%?\s*)?\)|hsla?\(\s*\d*(?:\.\d*)?(?:deg|grad|rad|turn)?\s*,\s*(?:\d*(?:\.\d*)?%|0)\s*,\s*(?:\d*(?:\.\d*)?%|0)\s*(?:,\s*\d*(?:\.\d*)?%?\s*)?\)|h(?:sla?|wb)\(\s*\d*(?:\.\d*)?(?:deg|grad|rad|turn)?\s+\d*(?:\.\d*)?%?\s+\d*(?:\.\d*)?%?\s*(?:\/\s*\d*(?:\.\d*)?%?\s*)?\))$/
const num = String.raw`\d*(?:\.\d*)?`;
const percent = `(?:${num}%|0)`;
const numOrPercent = `${num}%?`;
const alpha = numOrPercent;
const hue = `${num}(?:deg|grad|rad|turn)?`;

const colorFuncs = [
  // Hex colors: #000, #0000, #000000, #00000000
  `#(?:[0-9a-fA-F]{3}){1,2}`,
  `#(?:[0-9a-fA-F]{4}){1,2}`,
  // Legacy rgb/rgba: rgba(1,2,3,0.5)
  String.raw`rgba?\(\s*${num}\s*,\s*${num}\s*,\s*${num}\s*(?:,\s*${alpha}\s*)?\)`,
  String.raw`rgba?\(\s*${percent}\s*,\s*${percent}\s*,\s*${percent}\s*(?:,\s*${alpha}\s*)?\)`,
  // Modern rgb/rgba: rgba(1 2 3/0.5)
  String.raw`rgba?\(\s*${numOrPercent}\s+${numOrPercent}\s+${numOrPercent}\s*(?:/\s*${alpha}\s*)?\)`,
  // Legacy hsl/hsla: hsl(1deg,2%,3%,0.5)
  String.raw`hsla?\(\s*${hue}\s*,\s*${percent}\s*,\s*${percent}\s*(?:,\s*${alpha}\s*)?\)`,
  // Modern hsl/hsla/hwb: hsla(1deg 2% 3%/0.5)
  String.raw`h(?:sla?|wb)\(\s*${hue}\s+${numOrPercent}\s+${numOrPercent}\s*(?:/\s*${alpha}\s*)?\)`,
];

export const ColorRegex = new RegExp(`^(${colorFuncs.join("|")})$`);

This regex doesn't recognize keywords and more advanced color functions, but for my use case I don't need that much specificity. You can extend this further by looking at what values are valid in the CSS specification.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment