Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify a given string is hex color format

Tags:

regex

colors

I'm looking for a regular expression to validate hex colors in ASP.NET C# and
am also looking code for validation on server side.

For instance: #CCCCCC

like image 230
Avinash Avatar asked Oct 28 '09 10:10

Avinash


People also ask

What hex color is 000000?

The color black with hexadecimal color code #000000 / #000 is a very dark shade of gray. In the RGB color model #000000 is comprised of 0% red, 0% green and 0% blue. In the HSL color space #000000 has a hue of 0° (degrees), 0% saturation and 0% lightness.

Is FFFF a color?

The color white with hexadecimal color code #ffffff / #fff is a very light shade of gray. In the RGB color model #ffffff is comprised of 100% red, 100% green and 100% blue. In the HSL color space #ffffff has a hue of 0° (degrees), 0% saturation and 100% lightness.


1 Answers

Note: This is strictly for validation, i.e. accepting a valid hex color. For actual parsing you won't get the individual parts out of this.

^#(?:[0-9a-fA-F]{3}){1,2}$ 

For ARGB:

^#(?:[0-9a-fA-F]{3,4}){1,2}$ 

Dissection:

^              anchor for start of string #              the literal # (              start of group  ?:            indicate a non-capturing group that doesn't generate backreferences  [0-9a-fA-F]   hexadecimal digit  {3}           three times )              end of group {1,2}          repeat either once or twice $              anchor for end of string 

This will match an arbitrary hexadecimal color value that can be used in CSS, such as #91bf4a or #f13.

like image 188
Joey Avatar answered Sep 21 '22 15:09

Joey