Java 检查该行是否包含/*
我想检查我的行是否包含Java 检查该行是否包含/*,java,code-analysis,readline,block-comments,Java,Code Analysis,Readline,Block Comments,我想检查我的行是否包含/*。我知道如何检查块注释是否在开头: /* comment starts from the beginning and ends at the end */ if(line.startsWith("/*") && line.endsWith("*/")){ System.out.println("comment : "+line); } 我想知道的是如何判断评论是这样的: something here /* comment*/ 或
/*
。我知道如何检查块注释是否在开头:
/* comment starts from the beginning and ends at the end */
if(line.startsWith("/*") && line.endsWith("*/")){
System.out.println("comment : "+line);
}
我想知道的是如何判断评论是这样的:
something here /* comment*/
或
您可以通过多种方式实现此目的,这里有一种: 在字符串中找到“/*”:
int begin = yourstring.indexOf("/*");
对“*/”执行相同的操作
这将得到两个整数,使用它们可以得到包含注释的子字符串:
String comment = yourstring.substring(begin, end);
尝试使用以下模式:
String data = "this is amazing /* comment */ more data ";
Pattern pattern = Pattern.compile("/\\*.*?\\*/");
Matcher matcher = pattern.matcher(data);
while (matcher.find()) {
// Indicates match is found. Do further processing
System.out.println(matcher.group());
}
这适用于
//单行和多行/*注释*/
Pattern pattern = Pattern.compile("//.*|/\\*((.|\\n)(?!=*/))+\\*/");
String code = " new SomeCode(); // comment \n" + " " + "/* multi\n"
+ " line \n" + " comment */\n"
+ "void function someFunction() { /* some code */ }";
Matcher matcher = pattern.matcher(code);
while (matcher.find()) {
System.out.println(matcher.group());
}
输出:
@苏雷沙塔。有一个问题。只是它不是以一个?
@sureshatta结尾,我想知道的是如何计算注释,它需要一个?
结尾,但这是一个问题。你考虑使用正则表达式吗?“我想知道的是如何计算注释,这是:“是我的问题哦,我的错…对不起。有一个问题。如果我有一个像这样的a*/string/*怎么办
?你颠倒开始和结束?我假设您将语法强加在注释的外观上,而您的模式不是这样。谢谢您指出这一点。我对代码做了适当的修改。请验证,它现在应该可以工作了。谢谢。我将尝试:)@ankur我应该使用什么包来获取Matcher?Matcher和Pattern类在java.util.regex包中提供。
Pattern pattern = Pattern.compile("//.*|/\\*((.|\\n)(?!=*/))+\\*/");
String code = " new SomeCode(); // comment \n" + " " + "/* multi\n"
+ " line \n" + " comment */\n"
+ "void function someFunction() { /* some code */ }";
Matcher matcher = pattern.matcher(code);
while (matcher.find()) {
System.out.println(matcher.group());
}
// comment
/* multi
line
comment */
/* some code */