I am working on a simple CSS parser in Python. Right now I want to extact all values from this string: "1px solid rgb(255, 255, 255)". Right now my pattern (which is not working) is: "\S+[^rgb]+". When I use it with string "1px solid rgb(255, 255, 255)", I get following:
...
>>> re.findall("\S+[^rgb]+", string)
("1px solid", "rgb(255, 255, 255)")
And I want it to be
("1px", "solid", "rgb(255, 255, 255)")
P.S.
Also, is there a better way for parsing CSS declaration? Currently my pattern is "[\s]?(\S+)[\s]?:[\s]?(.+)[\s]?;". Parsing "color: red;" gives me:
("color", "red")
You can try this:
(\S+)[ ]+(?:(\S+)[ ]+)?(rgb\([^)]+\))
http://regex101.com/r/vA4kH1
EDIT: Whatever you're trying to do, this is probably not the right way to handle it, because CSS syntax can be unpredictable. You can use tinycss, the Python CSS parser for something more sane:
http://pythonhosted.org/tinycss/
One last edit...
As per your solution, you're doing a findAll, which puts them in an array separately. You only need rgb() in there once, ignoring the space. This should work for the value pattern, which is cleaner than what you have. And also note, that you don't want to use "." for your rgb() expression. If you have rgb() 1px rgb() on the same line, regexes are greedy by default...it'll match as much as it can. Try this: r"(rgb([^)]+))|(\S+))"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With