Question

Looks like I need a little help with a regular expression to match RGB values. I've built the following expression but it doesn't find a match. It is also insufficient because I need to expand it to check for three digits and only a 0-255 value should exist.

For example. The following are all valid values I need to match against:

0,0,0
0, 0, 0
255,255,255
255, 255, 255

Here is what I have so far:

expression = re.compile(r'(\\d+),(,),(\\d+),(,),(\\d+)')
expression.match(text)
Was it helpful?

Solution

You can insure that the numbers are between 0 and 255 with a regex, but I highly recommend against it. An easier method here is to capture the numbers with a regex and check that they are between 0 and 255 by simply casting to an int and comparing:

>>> import re
>>> r = r"(\d+),\s*(\d+),\s*(\d+)"
>>> re.match(r, "0, 254,10").groups()
('0', '254', '10')
>>> all(0 <= int(group) <= 255 for group in re.match(r, "0, 254,10").groups())
True
>>> all(0 <= int(group) <= 255 for group in re.match(r, "0,256, 190").groups())
False
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top