2014-01-12 47 views
0

我有這樣的代碼識別的意見,並把它們打印在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

+1

重新「解析器不是一個選項」,不使用解析器不是一個選項,除非你想在''/ *字符串,而不是評論* /「', '「http:// foo」','「/path/*.txt」/ *文件路徑* /'。您需要識別可以包含註釋邊界的所有標記以正確識別註釋邊界。 –

+0

我該如何在該網站上做到這一點? – Unbound

+0

解析器肯定是一個選項,尤其是當你只需要詞法分析器部分時(通常最簡單的部分,如果你已經有了正則表達式支持)。謹防!這是一個相當深入的主題,要妥善進入;它是第二年課程的一部分,當我拿了CS(幾年前......) –

回答

2

你的格局,剝奪它的Java引用(和一些不必要的反斜槓)的,是這樣的:

(/\*((.| 
)*)\*/)|//.* 

這是不夠精細,但它只有貪婪量詞,這意味着它會從第一個/*匹配到最後*/。你要非貪婪量詞代替,得到這個模式:

(/\*((.| 
)*?)\*/)|//.* 

小的變化,大的後果,因爲它現在/*匹配後向第一*/。重新編碼爲Java代碼。

Pattern pattern = Pattern.compile("(/\\*((.|\n)*?)\\*/)|//.*"); 

(要知道,你是非常接近的東西它是明智的,以配合正則表達式的限制。事實上,它實際上是不正確,因爲你可能有串在/*//,但你可能會...)

3

用正則表達式解析源代碼是非常不可靠的。我建議你使用專門的解析器。使用antlr創建一個非常簡單。而且,由於您似乎在解析C源文件,因此您可以使用C grammar