-1

I have a large css file that I need to remove every rule from except the selector and font-size property and the curly braces. What would the RegEx be so select everything else?

The file is pretty much formatted like this all the way through.

.details h2 {margin: -14px 0 0 0; padding: 0 20px 24px 20px; font-size: 12px; color: #474747;}

I need it to end up like this.

.details h2 {font-size: 12px;}

JustinS
  • 1
  • 2

2 Answers2

1

I Sublime Text I can use:

Find: \{.*(font-size\:\s*\d+px\;).*\}?
Replace: \{ $1 \}

If the css is split over multiple-lines (as it should be ;)) then it requires a little more effort. Well, I would probably consider two or three separate replace operations.

Andy G
  • 19,232
  • 5
  • 47
  • 69
  • Of course, the font-size may not always be set in pixels. – Andy G Jul 02 '13 at 00:36
  • @JustinS, keep in mind that `font-size` may be specified in something other than pixels, and (as this answer states), multi-line rules will be a problem. If Andy's solution meets your needs, you can always use the slightly more robust search `\{.*(font-size:\s*[^;}]).*\}`. For a solution that spans multiple lines, see my solution. – Ethan Brown Jul 02 '13 at 00:48
1

Well, to do this 100% ironclad, you'd probably have to write a CSS parser, which is no walk in the park. However, you can solve this for most cases with regular expressions. The key really is not to try to do too much in a single regular expression (a common mistake). My solution involves two separate regular expressions: one to parse out the rules, and the other to pick the 'font-size' declarations from the declaration block. You didn't say what language or tools you had available, but I implemented this in JavaScript:

var css = $('style').text();   // this will grab the CSS of the page it's on...you can
                               // use whatever CSS you want, of course; this is just
                               // a string containing CSS

// join all lines by removing carriage returns; otherwise we'll run into
// lots of problems trying to grok rules that span multiple lines
css = css.replace( /\n/g, '' );

// match all rules, and separate into selectors and declarations
css = css.replace(/\s*([^{]*)\s*\{(.*?)\}/g, function(match,selector,declarations) {
    // see if font-size is among the declarations; if so, capture it's value
    var fsMatch = declarations.match( /\bfont-size\s*:\s*([^;]+?)\s*(;|$)/i );
    // if font-size is present, return only that declaration, otherwise return empty
    return fsMatch ?
        selector + ' { font-size: ' + fsMatch[1] + '; }\n' :
        '';
});

// now the 'css' variable contains the CSS you're looking for

Note that this solution produces pretty clean-looking CSS, too.

See a live example here:

http://jsfiddle.net/yLjCe/2/

Ethan Brown
  • 26,892
  • 4
  • 80
  • 92