Regular Expressions 101

Community Patterns

Community Library Entry

2

Regular Expression
ECMAScript (JavaScript)

/
^\s*(color|background[-color]*||[a-zA-Z0-9-_]+)??[\s:=]*[\s]*(?:(\b(rgb)\s*?\(\s*?(000|0?\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\s*?,\s*?(000|0?\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\s*?,\s*?(000|0?\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\s*?\))|(\b(rgba)\s*?\(\s*?(000|0?\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\s*?,\s*?(000|0?\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\s*?,\s*?(000|0?\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\s*?,\s*?(0|0\.\d*|1|1.0*)\s*?\))\B|(\b(transparent)|(inherit)|(initial)|(currentColor)|(var)[(]([-]{2}[^)]+)[)])|(#([a-fA-F0-9]){3,4})|(#([a-fA-F0-9]){6,8})|(\b(hsl)\s*?\(\s*?(000|0?\d{1,2}|[1-2]\d\d|3[0-5]\d|360)\s*?,\s*?(000|100|0?\d{2}|0?0?\d)%\s*?,\s*?(000|100|0?\d{2}|0?0?\d)%\s*?\)$)|(\b(hsla)\s*?\(\s*?(000|0?\d{1,2}|[1-2]\d\d|3[0-5]\d|360)\s*?,\s*?(000|100|0?\d{2}|0?0?\d)%\s*?,\s*?(000|100|0?\d{2}|0?0?\d)%\s*?,\s*?(0|0\.\d*|1|1.0*)\s*?\)\b))
/
gm

Description

Versatile, multiline matching of CSS colors of many common formats, including:

  • HEX-3: #123 (equivalent to #112233)
  • HEX-4: #FA0F ( ... #FFAA00FF)
  • HEX-6: #FF3300 ( ...#F30)
  • HEX-8: #FFAA00FF ( ...#FA0F)
  • RGB: rgb(0, 0, 0)
  • RGBA: rgba(255, 255, 255, 1.0)
  • HSL: hsl(100, 50%, 50%)
  • HSLA: hsla(100, 20%, 20%, 1.0)
  • Vars: var(--tw-color-name, #000000)
  • Misc: color: inherit; color: currentColor; color: initial;, etc.
  • With or without trailing semicolon or comma
  • Forgiving of whitespace issues
  • Allows property/declaration names (e.g. color: #fff), most other solutions do not.
Submitted by Nicholas Berlette (@nberlette) - 3 years ago