A Regular Expression that matches CSS colors

Recently I needed to have a Regular Expression which would match valid CSS colors. I wasn’t able to find any after searching the Internets for a while, so I wrote my own.

(#([0-9A-Fa-f]{3,6})\b)|

(aqua)|(black)|(blue)|(fuchsia)|

(gray)|(green)|(lime)|(maroon)|

(navy)|(olive)|(orange)|(purple)|

(red)|(silver)|(teal)|(white)|(yellow)|

(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,

\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,

\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|

(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\))

Just as a recap, a valid CSS color can be represented as a…

  1. named color, such as “red”, “green”, “blue”, “black”, etc.
  2. hexadecimal value, such as #ff0000 (red), #00ff00 (green), #0000ff (blue), #000000 (black), etc. Some hexadecimal values can be reduced to just three characters. For example, red is #f00 and green is #0f0.
  3. triplet consisting of the color’s RGB values, such as rgb(255,0,0) for red and rgb(0,255,0) for green.

The Regular Expression listed above should be able to handle any of the variants that a CSS color can throw at it.

  1. Wow. You’re good! Even I understood that!

  • SlappyTheFish Says:

    Works for me!

    In case anyone’s interested, here’s the original definition:
    http://www.w3.org/TR/CSS21/syndata.html#color-units

  • Leave a Reply