How to identify a given string is hex color format

前端 未结 7 2455
走了就别回头了
走了就别回头了 2020-12-07 15:27

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

7条回答
  •  悲哀的现实
    2020-12-07 15:57

    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.

提交回复
热议问题