从字符串中删除注释

时间:2013-09-19 05:14:15

标签: java

我想做一个获取字符串的函数,如果它有内联注释,它会删除它。

public class sample {

    public static void main(String[] args) {
        String code = "/**THIS IS SAMPLE CODE */ public class TestFormatter{public static void main(String[] args){int i =2; String s= \"name\";\\u give give change the values System.out.println(\"Hello World\");//sample}}";

        CodeFormatter codeFormatter = ToolFactory.createCodeFormatter(null);

        TextEdit textEdit = codeFormatter.format(
                CodeFormatter.K_COMPILATION_UNIT, code1, 0, code1.length(), 0,
                null);
        IDocument doc = new Document(code1);
        try {
            textEdit.apply(doc);
            System.out.println(doc.get());
        } catch (MalformedTreeException e) {
            e.printStackTrace();
        } catch (BadLocationException e) {
            e.printStackTrace();
        }
    }
}

我在textEdit.apply(doc)得到空指针异常。这是因为它不接受评论。

你能告诉我从字符串中删除评论的最佳方法是什么? (请不要建议太高级的解决方案)。

2 个答案:

答案 0 :(得分:1)

尝试

replaceAll("(?s)/\\*.*?\\*/", "")

示例:

String code = "/**THIS IS SAMPLE CODE */ public class TestFormatter{public static void main(String[] args){int i =2; String s= \"name\";\\\\u give give change the values System.out.println(\"Hello World\");//sample}}";
System.out.println(code.replaceAll("(?s)/\\*.*?\\*/", ""));

输出:

public class TestFormatter{public static void main(String[] args){int i =2; String s= "name";\\u give give change the values System.out.println("Hello World");//sample}}

<强> PS。

如果您还想删除上次评论//sample}}

然后使用split()

System.out.println(code.replaceAll("(?s)/\\*.*?\\*/", "").split("//")[0]);
// keep in Mind it will also Remove  }} from //sample}} 

输出:

 public class TestFormatter{public static void main(String[] args){int i =2; String s= "name";\u give give change the values System.out.println("Hello World");

答案 1 :(得分:1)

replaceAll("((/\\*)[^/]+(\\*/))|(//.*)", "")

这将删除单行,多行或文档注释。

兼容JavaScript的正则表达式为((/\*)[^/]+(\*/))|(//.*),您可以使用regexpal.com尝试。