先说结果:
我是测试出来了正则表达式,但是是针对三种注释,写了三种正则。
没有实现单一的正则表达式,支持所有的注释类型的。
代码你可以参考参考:
//单行注释
String commentsStr = "//this is single line comments";
Pattern singleLineCommentP = Pattern.compile("^//.*?$");
Matcher foundSingleLineComment = singleLineCommentP.matcher(commentsStr);
boolean foundSingle = foundSingleLineComment.matches();
System.out.println(foundSingleLineComment);
System.out.println(foundSingle);
/*单行注释*/
String doubleStarCommentStr = "/* this is double star comments */";
Pattern doubleStarCommentP = Pattern.compile("^/\\*.*?\\*/$");
Matcher foundDoubleStarComment = doubleStarCommentP.matcher(doubleStarCommentStr);
boolean foundDouble = foundSingleLineComment.matches();
System.out.println(foundDoubleStarComment);
System.out.println(foundDouble);
/*
*多行注释
*/
String multiLineComments = "/* \n" +
"* this is \n" +
"* multi line comment \n" +
"*/";
Pattern multiLineCommentP = Pattern.compile("^/\\*.*\\*/$", Pattern.DOTALL);
Matcher foundMultiLineComment = multiLineCommentP.matcher(multiLineComments);
boolean foundMulti = foundMultiLineComment.matches();
System.out.println(foundMultiLineComment);
System.out.println(foundMulti);
感兴趣的话,可以去看看我总结的:
crifan 正则表达式学习心得
(此处不给贴地址,请用google搜标题,即可找到帖子地址)
\/\*[\w\W]*?\*\/|\/\/.*
^//.*$|^/\*.*\*/$|^/\*\*.*$|^\*.*$|.*\*/$