How to identify a given string is hex color format

前端 未结 7 2453
走了就别回头了
走了就别回头了 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:55

    Based on MSalters' answer, but preventing an incorrect match, the following works

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

    Or for an optional hash # symbol:

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

    And without back references being generated:

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

提交回复
热议问题