-
-
Save clipperhouse/1201239 to your computer and use it in GitHub Desktop.
var minified = Regex.Replace(css, @"\s*([,>+;:}{]{1})\s*", "$1").Replace(";}", "}"); | |
// ...where css is a string containing valid CSS | |
// There are several ways to optimize this; I would use a compiled regex and | |
// put it in an extension method for ease of use | |
public static class Extensions { | |
static Extensions() // static constructor | |
{ | |
_cssregex = new Regex(@"\s*([,>+;:}{]{1})\s*", RegexOptions.Compiled); | |
} | |
private static Regex _cssregex; | |
public static string MinifyCss(this string s) | |
{ | |
if (s.IsNullOrEmpty()) | |
return s; | |
return _cssregex.Replace(s, "$1").Replace(";}", "}"); | |
} | |
} |
Good points! The comments should be easy to regex out; the literal content less so.
How would you go about the literal stuff? Replace each instance with a placeholder token, minify, then re-replace the tokens with original content?
Quotes cannot be nested, so however you solve the block comments problem should work equally as well for quoted content. You might have to run multiple passes however(?) because there could be a lone quote inside of a comment.
There’s a difference between the comments and the quoted stuff I think. Comments can be wiped out with little consideration for what’s in them. The quoted content needs to be “taken out of harm’s way”, then minify everything else, then put it back verbatim. An escaped quote within content would be just enough to make it a PITA. :)
(Yes, it would be a few distinct passes.)
Works well only 2 things I noticed, it doesn't remove comments and it messes with quoted text in content rules.
ul.fortunes > li:after { content: ", in my pants."; /* lolz */ }