Python - How to check if string is a HEX Color Code
Asked Answered
A

2

13

I need your help!

Im kinda new whats regarding python and "hex".

I have a site where people can enter their own HEX-Color for their messages.

So currently i have everything built in except the "isHEXColor" Check..

I realy dont know how i can be sure that the user gave a valid HEX-Color-Code.

Currently im just checking if the len is 6 digits, nothing more.

if not len(color) == 6: return error("HEX-Color" must contain 6 characters")

Can you might help me? And it should work for Python 2.5!

Aimless answered 14/5, 2015 at 15:36 Comment(2)
A similar question has been asked before. Check here #11592761 to see if that answer helps you.Waybill
Color codes don't have to contain 6 hex digits; they can contain anywhere from 1 to 12 digits. 6 is simply the most common usage.Humidifier
E
32

You could use a regular expression:

^#(?:[0-9a-fA-F]{3}){1,2}$

For using regular expression in python https://docs.python.org/2/library/re.html

import re
hex_string = '#ffffff' # Your Hex

match = re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', hex_string)

if match:                      
  print 'Hex is valid'

else:
  print 'Hex is not valid'
Erigena answered 14/5, 2015 at 15:53 Comment(0)
E
5

teoreda's proposition to use regex seems fine to me, but I think the right regex is rather:

^#(?:[0-9a-fA-F]{1,2}){3}$

(each color (r, g and b) has 1 or 2 digits and there are 3 colors)

Erysipeloid answered 14/5, 2015 at 15:58 Comment(1)
This would allow a hex code with a length that is not 3 or 6. regex101.com/r/oXR9FV/1Suspiration

© 2022 - 2024 — McMap. All rights reserved.