tags:

views:

358

answers:

2

I'm looking for a regular expression to validate hex colors in asp.net C#. and also looking code for validate in server side

For instance: #CCCCCC

+4  A: 
^#(?:[0-9a-fA-F]{3}){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.

Joey
A: 

Minor disagreement with the other solution. I'd say

^#([0-9a-fA-F]{2}){3}|([0-9a-fA-F]){3}$

The reason is that this (correctly) captures the individual RGB components. The other expression broke #112233 in three parts, '#' 112 233. The syntax is actually '#' (RR GG BB) | (R G B)

The slight disadvantage is more backtracking is required. When parsing #CCC you don't know that the second C is the green component until you hit the end of the string; when parsing #CCCCCC you don't know that the second C is still part of the red component until you see the 4th C.

MSalters
This regex would also match #1234 and #12345. However, there can be only either 3 digits or 6 digits. This RE allows anything between 3 and 6 digits. If you truly wanted to capture the correct structure, then you'd have to use `#([1-9a-fA-F]{3}|[1-9a-fA-F]{6})`. If you want to capture the individual color components it gets more complex (your suggestion doesn't do that as well).
Joey
On second thought, you're right - fixing it.
MSalters
For pure validation purposes (i. e. whether a value is actually a possible and correct one) however, I find it easier to look at the apparent structure of the string and not at the specified one. At least in this case the resulting RE is simpler.
Joey