Ruby Regex matches gray

I want the Ruby regex to match the six-color shade of gray.

So it will match

#000000 #ababab #ffffff 

but NOT

 #ccddcc #afafa0 

and etc.

+7
source share
2 answers

\h is the ruby โ€‹โ€‹regular expression code for hex. (...) captures the load, and \1 allows you to refer to the first profile:

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

in irb:

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

Try the following:

 ^#([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 one character 3 times (matching #AAA ), or repeating double char 3 times (matching #666666 and #121212 ).

+3
source

All Articles