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 "".
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 "".
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.
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.
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 (.*?
).
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.