用正则表达式在java怎么去匹配注释 //的单行注释 /*单行注释*/ /* *多行注释 */
3个回答
展开全部
先说结果:
我是测试出来了正则表达式,但是是针对三种注释,写了三种正则。
没有实现单一的正则表达式,支持所有的注释类型的。
代码你可以参考参考:
//单行注释
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搜标题,即可找到帖子地址)
我是测试出来了正则表达式,但是是针对三种注释,写了三种正则。
没有实现单一的正则表达式,支持所有的注释类型的。
代码你可以参考参考:
//单行注释
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]*?\*\/|\/\/.*
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
^//.*$|^/\*.*\*/$|^/\*\*.*$|^\*.*$|.*\*/$
追问
不能用呀
追答
可以用啊
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询