Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the regex of a CSS selector

Tags:

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?

like image 432
Freddy Boucher Avatar asked Sep 25 '12 03:09

Freddy Boucher


People also ask

Can you use regex in CSS selector?

You can use regular expressions (regex) and cascading style sheet (CSS) selectors as operators wherever trigger filters are used.

What is the syntax of CSS selector?

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.


2 Answers

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.

like image 158
Dai Avatar answered Sep 29 '22 18:09

Dai


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:

  • bad sample with block comment: http://regexr.com?328sd
like image 32
Freddy Boucher Avatar answered Sep 29 '22 16:09

Freddy Boucher