Joe*_*oey 138
^#(?:[0-9a-fA-F]{3}){1,2}$
Run Code Online (Sandbox Code Playgroud)
解剖:
^ 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
Run Code Online (Sandbox Code Playgroud)
这将匹配可在CSS中使用的任意十六进制颜色值,例如#91bf4a或#f13.
注意:不支持RGBA十六进制颜色值.
MSa*_*ers 16
与其他解决方案略有不同.我会说
^#(([0-9a-fA-F]{2}){3}|([0-9a-fA-F]){3})$
Run Code Online (Sandbox Code Playgroud)
原因是这(正确)捕获了各个RGB组件.另一个表达式分为#112233,分为三部分,'#'112 233.语法实际上是'#'(RR GG BB)| (RGB)
轻微的缺点是需要更多的回溯.在解析#CCC时,你不知道第二个C是绿色组件,直到你到达字符串的末尾; 在解析#CCCCCC时,你不知道第二个C仍然是红色组件的一部分,直到你看到第四个C.
这应该匹配任何#rgb, #rgba, #rrggbb, 和#rrggbbaa语法:
/^#(?:(?:[\\da-f]{3}){1,2}|(?:[\\da-f]{4}){1,2})$/i\nRun Code Online (Sandbox Code Playgroud)\n\n分解:
\n\n^ // start of line\n# // literal pound sign, followed by\n(?: // either:\n (?: // a non-capturing group of:\n [\\da-f]{3} // exactly 3 of: a single digit or a letter 'a'\xe2\x80\x93'f'\n ){1,2} // repeated exactly 1 or 2 times\n| // or:\n (?: // a non-capturing group of:\n [\\da-f]{4} // exactly 4 of: a single digit or a letter 'a'\xe2\x80\x93'f'\n ){1,2} // repeated exactly 1 or 2 times\n)\n$ // end of line\ni // ignore case (let 'A'\xe2\x80\x93'F' match 'a'\xe2\x80\x93'f')\nRun Code Online (Sandbox Code Playgroud)\n\n请注意,上面的内容并不等同于以下语法,这是不正确的:
\n\n/^#(?:[\\da-f]{3,4}){1,2}$/i\nRun Code Online (Sandbox Code Playgroud)\n\n这将允许一组 3 后跟一组 4,例如#1234567,这不是有效的十六进制颜色。
如果您也想接受命名颜色和 rgb(a,b,c)。最后的“i”不区分大小写。
HTML 颜色(#123,不接受 RGB)
/^(#[a-f0-9]{6}|black|green|silver|gray|olive|white|yellow|maroon|navy|red|blue|purple|teal|fuchsia|aqua)$/i
Run Code Online (Sandbox Code Playgroud)
CSS 颜色(#123,接受 RGB)
/^(#[a-f0-9]{6}|#[a-f0-9]{3}|rgb *\( *[0-9]{1,3}%? *, *[0-9]{1,3}%? *, *[0-9]{1,3}%? *\)|rgba *\( *[0-9]{1,3}%? *, *[0-9]{1,3}%? *, *[0-9]{1,3}%? *, *[0-9]{1,3}%? *\)|black|green|silver|gray|olive|white|yellow|maroon|navy|red|blue|purple|teal|fuchsia|aqua)$/i
Run Code Online (Sandbox Code Playgroud)
所有答案都提到了 RGB 格式,这里是 ARGB 格式的正则表达式:
^#[0-9a-fA-F]{8}$|#[0-9a-fA-F]{6}$|#[0-9a-fA-F]{4}$|#[0-9a-fA-F]{3}$
Run Code Online (Sandbox Code Playgroud)