tags:

views:

82

answers:

4

I am new to regular expressions. I want to use java's replaceAll() function to replace any CSS comments in a string.

Basically I want to use regex to search for anything that is surrounded by "/*" and "*/" and replace it with "".

+2  A: 

It can't be done. You can find most comments in most situations with regular expressions, but CSS is not a regular grammar so you can't find all the cases with regular expressions.

Paul Tomblin
Hmmm. How would you suggest I do this?
Jacob
@Jacob - look for an existing tool that does the job; e.g. do a Google search for "CSS compress". Or if you want to embed the code for doing this, try "CSS parser java".
Stephen C
+1  A: 

You might consider running the javascript through one of the many javascript/CSS minimizers available. Among other tricks to make it smaller it also removes the comments.

Peter Tillemans
i am using Java. not javascript
Jacob
I meant CSS, thank for correcting me. I guess I am saying is that Java regexes is not the best tool. It is pretty easy to get a 95% solution but due to the complexity of having all combinations of multiple languages, escape sequences, /* ... */ in strings or CDATA sections the regexes quickly become unmaintainable. Regexes are a powerful tool when used in moderation.
Peter Tillemans
+1  A: 

One example where a simple regular expression fails is:

body { font-family: "/* this is not a comment */"; }

But if you don't care about these cases, you can simply go with this:

str.replaceAll("/\\*.*?\\*/", "");

The match starts at the first /* it finds and then looks for the next */, with as few characters in between as possible (.*?).

Roland Illig
A: 

I suggest to use the YUI compressor for this. Download the JAR, put in classpath and use it as follows:

BufferedReader reader = null;
BufferedWriter writer = null;
try {
    reader = new BufferedReader(new InputStreamReader(new FileInputStream("/path/to/original.css"), "UTF-8"));
    writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("/path/to/compressed.css"), "UTF-8"));
    new CssCompressor(reader).compress(writer, -1);
} finally {
    if (writer != null) try { writer.close(); } catch (IOException logOrIgnore) {}
    if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}

It however not only removes the comments, but it also minifies the CSS. Not sure if this suits the requirements, but it has benefits as well. We use it here during automated deploys of the webapp.

BalusC