Pop*_*oko 4 java string comments
我想做一个获取字符串的函数,如果它有内联注释,它会删除它.我知道这听起来很简单,但我想确保我这样做是正确的,例如:
private String filterString(String code) {
// lets say code = "some code //comment inside"
// return the string "some code" (without the comment)
}
Run Code Online (Sandbox Code Playgroud)
我想了两种方法:随意提出建议
你能告诉我什么是最好的方式并告诉我应该怎么做?(请不要建议太高级的解决方案)
编辑:这可以用Scanner对象以某种方式完成吗?(我还是使用这个对象)
如果您想要一个更高效的正则表达式来真正匹配所有类型的注释,请使用以下一个:
replaceAll("(?:/\\*(?:[^*]|(?:\\*+[^*/]))*\\*+/)|(?://.*)",""));
Run Code Online (Sandbox Code Playgroud)
来源:http://ostermiller.org/findcomment.html
编辑:
另一个解决方案,如果你不确定使用正则表达式是设计一个如下的小自动机:
public static String removeComments(String code){
final int outsideComment=0;
final int insideLineComment=1;
final int insideblockComment=2;
final int insideblockComment_noNewLineYet=3; // we want to have at least one new line in the result if the block is not inline.
int currentState=outsideComment;
String endResult="";
Scanner s= new Scanner(code);
s.useDelimiter("");
while(s.hasNext()){
String c=s.next();
switch(currentState){
case outsideComment:
if(c.equals("/") && s.hasNext()){
String c2=s.next();
if(c2.equals("/"))
currentState=insideLineComment;
else if(c2.equals("*")){
currentState=insideblockComment_noNewLineYet;
}
else
endResult+=c+c2;
}
else
endResult+=c;
break;
case insideLineComment:
if(c.equals("\n")){
currentState=outsideComment;
endResult+="\n";
}
break;
case insideblockComment_noNewLineYet:
if(c.equals("\n")){
endResult+="\n";
currentState=insideblockComment;
}
case insideblockComment:
while(c.equals("*") && s.hasNext()){
String c2=s.next();
if(c2.equals("/")){
currentState=outsideComment;
break;
}
}
}
}
s.close();
return endResult;
}
Run Code Online (Sandbox Code Playgroud)
执行此操作的最佳方法是使用正则表达式.首先找到/**/
注释然后删除所有//
commnets.例如:
private String filterString(String code) {
String partialFiltered = code.replaceAll("/\\*.*\\*/", "");
String fullFiltered = partialFiltered.replaceAll("//.*(?=\\n)", "")
}
Run Code Online (Sandbox Code Playgroud)
使用正则表达式替换来查找常量子字符串之前的子字符串有点多。
您可以使用indexOf()
检查注释开始的位置并substring()
获取第一部分来完成此操作,例如:
String code = "some code // comment";
int offset = code.indexOf("//");
if (-1 != offset) {
code = code.substring(0, offset);
}
Run Code Online (Sandbox Code Playgroud)