我正在开发一个个人项目,我需要从这样的输入字符串中提取实际的评论。
情况1:/*一些有用的文本*/
输出:一些有用的文本
情况 2:/*** 其格式令人讨厌**/
输出:格式令人讨厌
情况3:
/**
More useful
information
*/
输出:更多有用信息
案例4:
/**
Prompt the user to type in
the number. Assign the number to v
*/
输出:提示用户输入数字。将数字分配给v
我正在使用Java工作,我尝试使用诸如String.replace
之类的朴素方法来替换/*
和*/
,但是自从注释可以采用与上面不同的方式格式化,replace
方法似乎不是执行此操作的可行方法。如何使用正则表达式实现上述输出?
Here是我正在使用的测试注释文件。
最佳答案
尝试类似:
"/\\*+\\s*(.*?)\\*+/"
点也应该匹配新行:
Pattern p = Pattern.compile("/\\*+\\s*(.*?)\\*+/", Pattern.DOTALL);
编辑
Pattern p = Pattern.compile("/\\*+\\s*(.*?)\\*+/", Pattern.DOTALL);
Matcher m = p.matcher("/*** This is formatted obnoxiously**/");
m.find();
String sanitizedComment = m.group(1);
System.out.println(sanitizedComment);
关于Java:使用正则表达式从 block 注释中去除斜杠和星号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16053913/