Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex parsing of CSS @media queries (and other nested selectors)

I'm working on a node script which uses regex to parse CSS files, and it works perfectly... except when dealing with @media queries. The problem is due to the nested curly-brackets which are giving me fits. I essentially want to create a capturing group of ALL the content inside a media query: Here's what I've got so far.

@media[^{]+\{([^}]+)}\s*}

This works fine on something simple like:

@media (max-width: 868px) {
  aside .size-toggle {
    display: none;
  }
}

But can't pick up multiple nested rules, like this:

@media (max-width: 767px) {
  #wrapper.sidebar-display aside {
    left: 0;
    transition: all 0.5s ease;
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -ms-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
  }
  #wrapper.sidebar-display #top-nav {
    left: 0;
    right: -194px;
  }
}

How do I need to modify my regex so that the capturing group contains all the selectors and rules inside each individual @media query?

like image 221
Mordred Avatar asked Mar 10 '14 22:03

Mordred


1 Answers

Try this regex:

/@media[^{]+\{([\s\S]+?})\s*}/g

Demo

http://regex101.com/r/iT2eR5

like image 187
Stephan Avatar answered Oct 19 '22 22:10

Stephan