parml
parml

Reputation: 649

Regex for inconsistent html color codes

I am developing a script that will be used as a pre-commit git hook that will enforce a specific element of coding style: In an html color code of format #mmm or #mmmmmm use either all small or all capital letters.

I need a regex that

will match:

will not match:

I have a regex that cannot satisfy the length constraint and matches too much

[a-fA-F\d]*[a-f][a-fA-F\d]*[A-F][a-fA-F\d]*|[a-fA-F\d]*[A-F][a-fA-F\d]*[a-f][a-fA-F\d]*
                                           ^ or here

The reason for not matching invalid color codes (length not 3 or 6, letter not hexa) is I want to minimize the situation where a commit is rejected because somebody used tokens like like #s23 in comments (may be valid business related references).

I know I can use negative lookbehind on color, background, background-color and all places where a color is expected, but before I go there, is there something evidently simple that I am missing?

Any flavor of regex welcome.

Upvotes: 2

Views: 60

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149010

Here's my stab at it (Demo):

#(?!([0-9A-F]+|[0-9a-f]+)\b)(?i:[0-9A-F]{3}){1,2}\b

The first group is a negative lookahead that will exclude any sequence of consistent letters (either [0-9A-F]+ or [0-9a-f]+). The second block will match any sequence of 3 or 6 hexadecimal digits.

Note: The i in the second group applies the case-insensitive flag to that group alone, so it's equivalent to (?:[0-9A-Fa-f]{3}).

Upvotes: 1

Related Questions