Regular Expressions 101

Community Patterns

1...456

Community Library Entry

11

Regular Expression
ECMAScript (JavaScript)

/
^(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*?\))$|^(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*?\))$|^(transparent)$|^(#([a-fA-F0-9]){3})$|^(#([a-fA-F0-9]){6}$)|(^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*?\)$)|(^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*?\)$)$
/

Description

This may be useful or not to test whether a given string is a valid (more or less) html color value. It matches color values such as:

  • #123 - short hex color value
  • #123456 - hex color value
  • rgb(255,255,0) - rgb color value
  • rgba(255,255,0,1.0) - rgba color value
  • hsl(360,100%,100%) - hsl color value
  • hsla(360,100%,100%,0.5334) - hsla color value

Regex allows whitespaces between i.e. rgb and (, also between numbers and commas, but not in value like 55% between number and percentage. To change this behaviour simply remove \s*? from appriopriate places.

Submitted by grouch - 10 years ago