简体   繁体   English

从字符串中删除注释

[英]Removing the comments from a string

I'd like to do a function which gets a string and in case it has inline comments it removes it. 我想做一个获取字符串的函数,如果它有内联注释,它会删除它。

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();
        }
    }
}

I am getting null pointer exception at textEdit.apply(doc) . 我在textEdit.apply(doc)得到空指针异常。 This is because it is not accepting the comments. 这是因为它不接受评论。

Can you tell me what's the best way to remove the comments from the string? 你能告诉我从字符串中删除注释的最佳方法是什么? (please don't advice too advanced solutions). (请不要建议太高级的解决方案)。

Try 尝试

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

Example: 例:

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)/\\*.*?\\*/", ""));

Output: 输出:

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. PS。

if you also want to remove last comments //sample}} 如果你还想删除最后的评论//sample}}

Then use split() 然后使用split()

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

Output: 输出:

 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");
replaceAll("((/\\*)[^/]+(\\*/))|(//.*)", "")

This will remove single line, multi-line or doc comments. 这将删除单行,多行或文档注释。

The JavaScript compatible regex is ((/\\*)[^/]+(\\*/))|(//.*) , which you can try with regexpal.com. JavaScript兼容的正则表达式是((/\\*)[^/]+(\\*/))|(//.*) ,您可以尝试使用regexpal.com。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM