从字符串中删除注释

编程入门 行业动态 更新时间:2024-10-26 20:29:03
本文介绍了从字符串中删除注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

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

I am getting null pointer exception at 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).

推荐答案

尝试

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}}

if you also want to remove last comments //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");

更多推荐

从字符串中删除注释

本文发布于:2023-11-11 08:06:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1577840.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   注释

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!