Regex for matching CSS hex colors

后端 未结 5 1085
傲寒
傲寒 2021-02-02 07:33

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

This is what I have now:

Code:

$css = <<

        
5条回答
  •  遇见更好的自我
    2021-02-02 08:15

    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
    

提交回复
热议问题