Created
September 7, 2011 17:50
-
-
Save clipperhouse/1201239 to your computer and use it in GitHub Desktop.
CSS minifier in one line
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(";}", "}"); | |
} | |
} |
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.)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.