Remove all the single-line comments from a block of text - Java java.lang

Java examples for java.lang:String Strip

Description

Remove all the single-line comments from a block of text

Demo Code


import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.Arrays;
import java.util.Locale;
import java.util.SortedSet;
import java.util.TreeSet;

public class Main{
    private static Log log = Log.getLog(JavascriptUtil.class);
    /**/* w ww.ja v a 2s. co m*/
     * How does a single line comment start?
     */
    private static final String COMMENT_SL_START = "//";
    /**
     * Sometimes we need to retain the comment because it has special meaning
     */
    private static final String COMMENT_RETAIN = "#bss.serviceframework";
    /**
     * Remove all the single-line comments from a block of text
     * @param text The text to remove single-line comments from
     * @return The single-line comment free text
     */
    public static String stripSingleLineComments(String text) {
        if (text == null) {
            return null;
        }

        try {
            StringBuffer output = new StringBuffer();

            BufferedReader in = new BufferedReader(new StringReader(text));
            while (true) {
                String line = in.readLine();
                if (line == null) {
                    break;
                }

                // Skip @DWR comments
                if (line.indexOf(COMMENT_RETAIN) == -1) {
                    int cstart = line.indexOf(COMMENT_SL_START);
                    if (cstart >= 0) {
                        line = line.substring(0, cstart);
                    }
                }

                output.append(line);
                output.append('\n');
            }

            return output.toString();
        } catch (IOException ex) {
            log.error("IOExecption unexpected.", ex);
            throw new IllegalArgumentException("IOExecption unexpected.");
        }
    }
}

Related Tutorials