I'd like to parse a CSS file and add another CSS selector before every CSS selector.
From:
p{margin:0 0 10px;}
.lead{margin-bottom:20px;font-size:21px;font-weight:200;line-height:30px;}
I'd like:
.mySelector p{margin:0 0 10px;}
.mySelector .lead{margin-bottom:20px;font-size:21px;font-weight:200;line-height:30px;}
But my CSS file is really complex (in fact it is the bootstrap CSS file), so the regex should match all CSS selectors.
For now, I have this regex:
([^\r\n,{};]+)(,|{)
And you can see the result here http://regexr.com?328ps, but as you can see, there are a lot of matches that shouldn't match.
For example:
text-shadow:0 -1px 0 rgba(0,
matches positive but it shouldn't
Does someone have a solution?
You can use regular expressions (regex) and cascading style sheet (CSS) selectors as operators wherever trigger filters are used.
A CSS Syntax rule consists of a selector, property, and its value. The selector points to the HTML element where CSS style is to be applied. The CSS property is separated by semicolons. It is a combination of selector name followed by the property: value pair that is defined for the specific selector.
There isn't one. CSS selectors are not an example of a "Regular Language" and so cannot be parsed by a Regular Expression. You will need to build your own parser based on the CSS grammar specification: http://www.w3.org/TR/css3-syntax/#detailed-grammar
CSS is described as an LL(1) grammar, so you're probably better off using a tool like Yacc to generate your parser for you.
So I've finally found a REGEX that works for my requirements
([^\r\n,{}]+)(,(?=[^}]*{)|\s*{)
The key point was to add a Positive lookahead to avoid bad matches
(?=[^}]*{)
You can see the result here: http://regexr.com?328s7
The only precaution that I can recommend is to remove every block comment:
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