Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for matching CSS hex colors

I'm trying to write regex that extracts all hex colors from CSS code.

This is what I have now:

Code:

$css = <<<CSS  /* Do not match me: #abcdefgh; I am longer than needed. */  .foo {     color: #cccaaa; background-color:#ababab; }  #bar {     background-color:#123456 } CSS;  preg_match_all('/#(?:[0-9a-fA-F]{6})/', $css, $matches); 

Output:

Array (     [0] => Array         (             [0] => #abcdef             [1] => #cccaaa             [2] => #ababab             [3] => #123456         )  ) 

I don't know how to specify that only those colors are matched which ends with punctuation, whitespace or newline.

like image 839
Hemaulo Avatar asked Oct 11 '12 10:10

Hemaulo


People also ask

What is the regular expression for a valid HTML hex color value?

regex = "^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$"; Where: ^ represents the starting of the string. # represents the hexadecimal color code must start with a '#' symbol.

Which of these regular expression matches hex color code e74c3c?

#e74c3c Color Information Whereas in a CMYK color space, it is composed of 0% cyan, 67.1% magenta, 74% yellow and 9.4% black. It has a hue angle of 5.6 degrees, a saturation of 78.1% and a lightness of 57.1%. #e74c3c color hex could be obtained by blending #ff9878 with #cf0000.

Can you use hex for color CSS?

The most common way to specify colors in CSS is to use their hexadecimal (or hex) values. Hex values are actually just a different way to represent RGB values. Instead of using three numbers between 0 and 255, you use six hexadecimal numbers. Hex numbers can be 0-9 and A-F.

How do you check if a hex color is valid or not?

It starts with the '#' symbol. Then it is followed by the letters from a-f, A-F and/or digits from 0-9. The length of the hexadecimal color code should be either 6 or 3, excluding '#' symbol. For example: #abc, #ABC, #000, #FFF, #000000, #FF0000, #00FF00, #0000FF, #FFFFFF are all valid Hexadecimal color codes.


1 Answers

Since a hex color code may also consist of 3 characters, you can define a mandatory group and an optional group of letters and digits, so the long and elaborate notation would be:

/#([a-f]|[A-F]|[0-9]){3}(([a-f]|[A-F]|[0-9]){3})?\b/ 

Or if you want a nice and short version, you can say that you want either 1 or 2 groups of 3 alphanumeric characters, and that they should be matched case insensitively (/i).

/#([a-f0-9]{3}){1,2}\b/i 

Instead of [a-f0-9] you can also write [[:xdigit:]], if the regex engine supports this posix character class. In this case you can skip the /i at the end, and the whole formula is only two characters more, but arguably more descriptive.

/#([[:xdigit:]]{3}){1,2}\b/ 
like image 76
GolezTrol Avatar answered Sep 29 '22 11:09

GolezTrol