我有這樣的代碼識別的意見,並把它們打印在java中正則表達式評論匹配代碼不能正常工作
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Solution {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("(\\/\\*((.|\n)*)\\*\\/)|\\/\\/.*");
String code = "";
Scanner scan = new Scanner(System.in);
while(scan.hasNext())
{
code+=(scan.nextLine()+"\n");
}
Matcher matcher = pattern.matcher(code);
int nxtBrk=code.indexOf("\n");
while(matcher.find())
{
int i=matcher.start(),j=matcher.end();
if(nxtBrk<i)
{
System.out.print("\n");
}
System.out.print(code.substring(i,j));
nxtBrk = code.indexOf("\n",j);
}
scan.close();
}
}
現在,當我嘗試對這種輸入
/*This is a program to calculate area of a circle after getting the radius as input from the user*/
\#include<stdio.h>
int main()
{ //something
它輸出的代碼正確和唯一的意見。但是,當我給輸入
/*This is a program to calculate area of a circle after getting the radius as input from the user*/
\#include<stdio.h>
int main()
{//ok
}
/*A test run for the program was carried out and following output was observed
If 50 is the radius of the circle whose area is to be calculated
The area of the circle is 7857.1429*/
程序輸出整個代碼,而不是隻是註釋。我不知道添加最後幾行是什麼錯誤。
編輯:解析器不是一個選項,因爲我正在解決問題,我必須使用編程語言。鏈接https://www.hackerrank.com/challenges/ide-identifying-comments
重新「解析器不是一個選項」,不使用解析器不是一個選項,除非你想在''/ *字符串,而不是評論* /「', '「http:// foo」','「/path/*.txt」/ *文件路徑* /'。您需要識別可以包含註釋邊界的所有標記以正確識別註釋邊界。 –
我該如何在該網站上做到這一點? – Unbound
解析器肯定是一個選項,尤其是當你只需要詞法分析器部分時(通常最簡單的部分,如果你已經有了正則表達式支持)。謹防!這是一個相當深入的主題,要妥善進入;它是第二年課程的一部分,當我拿了CS(幾年前......) –