2015-05-22 65 views
0

我正試圖編寫一個匹配java文檔中的java文檔註釋的正則表達式,下面的代碼似乎沒有工作。正則表達式僅用於打開java文檔註釋

我特別想匹配的public class blah {

中第一次出現之前初始javadoc註釋下面的代碼發現JAVA_COMMENT_OPEN_TAG沒有任何問題,但找不到該JAVA_COMMENT_CLOSE_TAG標籤:

public class JavaDocParser { 

    private String JAVA_COMMENT_OPEN_TAG = "^/\\*\\**+"; 
    private String JAVA_COMMENT_CLOSE_TAG = "[.]+\\*{1}+/{1}$"; 
    private StringBuilder javaDocComment = new StringBuilder(); 

    public JavaDocParser(File javaFile) throws TestException { 
    parseJavaDocHeader(javaFile); 
    printJavaDocComment(); 
    } 

    private void parseJavaDocHeader(File javaFile) throws TestException { 
    BufferedReader br = null; 

    Pattern openPattern = Pattern.compile(JAVA_COMMENT_OPEN_TAG); 
    Pattern closePattern = Pattern.compile(JAVA_COMMENT_CLOSE_TAG); 

    boolean openTagFound = false; 
    boolean closeTagFound = false; 

    try { 

     br = new BufferedReader(new FileReader(javaFile)); 

     String line; 
     while((line = br.readLine()) != null) { 
     Matcher openMatcher = openPattern.matcher(line); 
     Matcher closeMatcher = closePattern.matcher(line); 

     if(openMatcher.matches()) { 
      System.out.println("OPEN TAG FOUND ON LINE: ====> " + line); 
      openTagFound = true; 
     } 

     if(closeMatcher.matches()) { 
      System.out.println("CLOSE TAG FOUND ON LINE: ====> " + line); 
      closeTagFound = true; 
     } 

     if(openTagFound) { 
      addToStringBuilder(line); 
     } else if(closeTagFound) { 
      break; 
     } 
     } 
    } catch (FileNotFoundException e) { 
     throw new TestException("The " + javaFile.getName() +" file provided could not be found. Check the file and try again."); 
     } catch (IOException e) { 
     throw new TestException("A problem was encountered while reading the .java file"); 
     } finally { 
     try { 
      if(br != null) { br.close(); } 
     } catch (IOException e) { 
     e.printStackTrace(); 
      } 
    } 
    } 

    private void addToStringBuilder(String stringToAdd) { 
    javaDocComment.append(stringToAdd + "\n"); 
    } 

    public String getJavaDocComment() { return javaDocComment.toString(); } 

    public void printJavaDocComment() { System.out.println(javaDocComment.toString()); } 
} 
+0

@JAL感謝這個問題有很大幫助。我需要改寫我的問題,因爲我試圖做一些更具體的事情。 –

+1

另外一般來說,正則表達式並不是解析器的替代品。 http://stackoverflow.com/questions/11905506/regular-expression-vs-string-parsing – markspace

+0

@markspace謝謝,這提出了一個觀點,我沒有太多的想法。如果人們打開和關閉他們的javadoc評論的方式不一致,我想我會考慮一個正則表達式。 –

回答

2

您可以使用以下方法:

private String JAVA_COMMENT_OPEN_TAG = "^/\*\*"; 
private String JAVA_COMMENT_CLOSE_TAG = ".*?\*+/$"; 

DEMO

+0

相同的結果,找到開始標記,但不是結束標記。 –

+0

@inquisitor檢查更新:) –

0

在你的正則表達式中,你包含了線條模式的開頭和結尾^$。但是你可以有空格之前或之後的評論

也許這將是更安全的使用方法:

private String JAVA_COMMENT_OPEN_TAG = "^\\s*/\\*\\**+"; 
private String JAVA_COMMENT_CLOSE_TAG = "[.]+\\*{1}+/{1}\\s*$"; 
+0

這隻能找到開始標籤。 –