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
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).
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论