开发者

Ruby Regex to Match Grayscale Color

I want a ruby regex to match a hex greyscale color.

So it would match

#000000
#ababab
#ffffff

but NOT

#ccddcc
#afafa0
开发者_JAVA技巧

etc.


\h is the ruby regex code for hexadecimal. (...) captures a submatch, and \1 lets you refer to the first submatch:

/#(\h\h)\1\1/

in irb:

>> %w{ #000000 #ababab #ffffff #ccddcc #afafa0 }.map { |s| s =~ /#(\h\h)\1\1/ }
=> [0, 0, 0, nil, nil]                                                         


Try this:

^#([0-9a-fA-F][0-9a-fA-F]?)\1\1$

which will match:

#000000
#aaa
#ababab
#ffffff

as you can see on Rubular: http://rubular.com/r/hDPrvr1dvu

It either repeats a single character 3 times (matching #AAA) or repeat a double char 3 times (matching #666666 and #121212).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜