I\'d like to parce a CSS file and add before every CSS selector another selector.
From:
p{margin:0 0 10px;}
.lead{margin-bottom:20px;font-size:21px;font-
A simple and readable regex is below:
[\#\.\w\-\,\s\n\r\t:]+(?=\s*\{)
you can test it on css code in this tool`
So finally I've found a way better way to do it.
I use a LESS editor (eg: http://lesstester.com/)
and simply nest my whole css file: .mySelector{ your css here }
Here's the solution I used for a similar problem. I wanted to remove all css rules that started with @
. For this I used the following regex:
@\s*.*\s*\{((?!\n\})[\s\S])+\n\}
It makes the assumption that the rule ends on a new line. That way it can sort of handle nested css rules.
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:
This is what I came up with:
(?<=\s)[^ ]*\s*\{[^\}]+\:[^\}]+\}
It's true that you can not select css selectors using regex, but you can select css rules using regex, so you can make the job done in the inverse way:
format css file in order to no have selectors and rules in the same line. your code should look like this:
p{
margin:0 0 10px;
}
.lead{
margin-bottom:20px;
font-size:21px;
font-weight:200;
line-height:30px;
}
select all rules (regex : (^(.)*;)
p{
margin:0 0 10px;
}
.lead{
margin-bottom:20px;
font-size:21px;
font-weight:200;
line-height:30px;
}
add some prefix to rules (example ####)
p{
####margin:0 0 10px;
}
.lead{
####margin-bottom:20px;
####font-size:21px;
####font-weight:200;
####line-height:30px;
}
select all lines not beginning with ####,not a return to line, and not a } (regex : ^[^#### \n }])
p{
####margin:0 0 10px;
}
.lead{
####margin-bottom:20px;
####font-size:21px;
####font-weight:200;
####line-height:30px;
}
add your css prefix
.my_class_prefix p{
####margin:0 0 10px;
}
.my_class_prefix .lead{
####margin-bottom:20px;
####font-size:21px;
####font-weight:200;
####line-height:30px;
}
delete the added prefix ####
.my_class_prefix p{
margin:0 0 10px;
}
.my_class_prefix .lead{
margin-bottom:20px;
font-size:21px;
font-weight:200;
line-height:30px;
}