regexvalidationqregexp

QRegEx to match a pure hue color


I am creating a QLineEditor to manually input a color in hex format. I want to set a validator to check if the input color is a pure HUE color.

All hue colors follow this pattern, being X any hex character [from 0-9 or A-F]:

#FF00XX
#00FFXX
#00XXFF
#XX00FF
#XXFF00
#FFXX00

I managed to check for a correct HEX color value: ^#([A-Fa-f0-9]{6})$, but I don't know how to extend the validator to accept only hue colors.

Any ideas?


Solution

  • The pattern you want is ^#(?:00(?:FFXX|XXFF)|FF(?:00XX|XX00)|XX(?:00FF|FF00))$.

    If you want XX to be any hex char, replace with [a-fA-F0-9]{2}. Then, the regex will look like

    ^#(?:00(?:FF[a-fA-F0-9]{2}|[a-fA-F0-9]{2}FF)|FF(?:00[a-fA-F0-9]{2}|[a-fA-F0-9]{2}00)|[a-fA-F0-9]{2}(?:00FF|FF00))$
    

    See the regex demo.

    If you do not want XX to match 00 and FF, replace XX with (?![fF]{2}|00)[a-fA-F0-9]{2}. Then, the regex will look like

    ^#(?:00(?:FF(?![fF]{2}|00)[a-fA-F0-9]{2}|(?![fF]{2}|00)[a-fA-F0-9]{2}FF)|FF(?:00(?![fF]{2}|00)[a-fA-F0-9]{2}|(?![fF]{2}|00)[a-fA-F0-9]{2}00)|(?![fF]{2}|00)[a-fA-F0-9]{2}(?:00FF|FF00))$
    

    See the regex demo.

    The (?![fF]{2}|00)[a-fA-F0-9]{2} part matches any two hex chars that are not equal to FF or 00 (case insensitive).