我正試圖編寫一個匹配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()); }
}
@JAL感謝這個問題有很大幫助。我需要改寫我的問題,因爲我試圖做一些更具體的事情。 –
另外一般來說,正則表達式並不是解析器的替代品。 http://stackoverflow.com/questions/11905506/regular-expression-vs-string-parsing – markspace
@markspace謝謝,這提出了一個觀點,我沒有太多的想法。如果人們打開和關閉他們的javadoc評論的方式不一致,我想我會考慮一個正則表達式。 –