Lindow Lindow - 1 year ago 61
Python Question

How to see if string list of rgb match regex pattern?

for security reasons I'd like to check if a string

is valid using regex.

Here's what the string list could look like :
'[255, 248, 234], [129, 85, 2], [2, 5, 55]'
, rgb must be in array, and well separated from each other with a coma, same for array separation with a coma, each value can contain from 1 to 3 values which should be numbers.

I know that you can check patterns but I have no idea on how to check on this specific regex

import re
pattern = re.compile("^[^0-9.]+$") #doesn't seem to be the good regex for what I'm trying

Any solution ?

Answer Source

Something like:

import re
from ast import literal_eval

inp = '[255, 248, 264], [129, 85, 2], [2, 5, 55]'
inp2 = '[5, 8, 4], [29, 85, 92], [255, 255, 255]'

def is_valid_rgb(inp):
    regex = r'^([1][0-9][0-9]|2[0-4][0-9]|25[0-5]|[0-9][0-9]|[0-9])$'
    evalinp = literal_eval(inp)
    for rgb in evalinp:
        for c in rgb:
            #if c < 0 or c > 255
            if not re.match(regex,str(c)):
                return False
    return True

print is_valid_rgb(inp) #False
print is_valid_rgb(inp2) #True

Of course, at this point might as well just do a check that c <= 255 and c >= 0 instead of using a regex. The problem with just using \d is that it doesn't catch numbers outside of the range as invalid values.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download