Removing unused CSS whitespace with ant replaceregexp

(Update 2017: These days, your frontend development toolchain should handle this.)

If common CSS compressors are not working for you, it may be a more defensive approach to reduce the filesize of a CSS file with simple regular expression replacement. For this example, I chose Apache Ant (using replaceregexp) to shrink the CSS files.

In this approach, I remove unused whitespace and linebreaks, but do not alter or optimize the CSS code at all.

Definition of the affected files

For easy reference, we define a fileset.

1
<fileset id="css.fileset" dir="your-css-folder" includes="**/*.css"/>

Comment removement

Remove comments in one or multiple lines.

1
2
3
4
5
6
7
<replaceregexp match="/\*.*\*/" replace="" flags="g" byline="true">
  <fileset refid="css.fileset"/>
</replaceregexp>

<replaceregexp match="/\*.+?\*/" replace="" flags="gs" byline="false">
  <fileset refid="css.fileset"/>
</replaceregexp>

Whitespace removement

Multiple whitespace characters are reduced to one, leading/ trailing whitespace is removed.

1
2
3
4
5
6
7
8
9
<replaceregexp match="\s+" replace=" " flags="g" byline="true">
 <fileset refid="css.fileset"/>
</replaceregexp>
<replaceregexp match="^\s+" replace="" flags="g" byline="true">
 <fileset refid="css.fileset"/>
</replaceregexp>
<replaceregexp match="\s+$" replace="" flags="g" byline="true">
 <fileset refid="css.fileset"/>
</replaceregexp

Merging of lines

Blocks of CSS statements are collapsed to a single line, multiple line feeds are removed.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<replaceregexp match="\{[\n\r]+" replace="{" flags="g" byline="false">
 <fileset refid="css.fileset"/>
</replaceregexp>
<replaceregexp match="[\n\r]+\}" replace="}" flags="g" byline="false">
 <fileset refid="css.fileset"/>
</replaceregexp>
<replaceregexp match="[\n\r]+\{" replace="{" flags="g" byline="false">
 <fileset refid="css.fileset"/>
</replaceregexp>
<replaceregexp match=";[\n\r]+" replace=";" flags="g" byline="false">
 <fileset refid="css.fileset"/>
</replaceregexp>
<replaceregexp match=",[\n\r]+" replace="," flags="g" byline="false">
 <fileset refid="css.fileset"/>
</replaceregexp>
<replaceregexp match="([\n\r])[\n\r]+" replace="\1" flags="g" byline="false">
 <fileset refid="css.fileset"/>
</replaceregexp>

This can all be done in a few seconds during compile time.

Share