How to identify a given string is hex color format

前端 未结 7 2376
走了就别回头了
走了就别回头了 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 16:07

    This should match any #rgb, #rgba, #rrggbb, and #rrggbbaa syntax:

    /^#(?:(?:[\da-f]{3}){1,2}|(?:[\da-f]{4}){1,2})$/i
    

    break down:

    ^            // start of line
    #            // literal pound sign, followed by
    (?:          // either:
      (?:          // a non-capturing group of:
        [\da-f]{3}   // exactly 3 of: a single digit or a letter 'a'–'f'
      ){1,2}       // repeated exactly 1 or 2 times
    |            // or:
      (?:          // a non-capturing group of:
        [\da-f]{4}   // exactly 4 of: a single digit or a letter 'a'–'f'
      ){1,2}       // repeated exactly 1 or 2 times
    )
    $            // end of line
    i            // ignore case (let 'A'–'F' match 'a'–'f')
    

    Notice that the above is not equivalent to this syntax, which is incorrect:

    /^#(?:[\da-f]{3,4}){1,2}$/i
    

    This would allow a group of 3 followed by a group of 4, such as #1234567, which is not a valid hex color.

    0 讨论(0)
提交回复
热议问题