What is the REGEX of a CSS selector

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

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 }


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.

Tags:

Css

Regex