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?
CodePudding user response:
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).
CodePudding user response:
The simplest way is to just use the pipe operator to cover all the six cases:
00[A-Fa-f0-9]{2}FF|00FF[A-Fa-f0-9]{2}|FF00[A-Fa-f0-9]{2}|FF[A-Fa-f0-9]{2}00|[A-Fa-f0-9]{2}00FF|[A-Fa-f0-9]{2}FF00
Obviously the pattern [A-Fa-f0-9]{2}
is repeated several times. To remove redundancy, you can save it in a separate variable and use string formatting to substitute it and form the pattern as shown above.
CodePudding user response:
If there are just 6 cases you can write this cases using boolean OR (|
)
(?<=#00FF|#FF00)[A-Fa-f0-9]{2}|[A-Fa-f0-9]{2}(?=00FF|FF00)|(?<=#00)[A-Fa-f0-9]{2}(?=FF)|(?<=#FF)[A-Fa-f0-9]{2}(?=00)