I'm trying to write a regex that matches java doc comments within java files and my code below doesn't seem to be working.
I'm specifically trying to match only the initial javadoc comments prior to the first occurrence of public class blah {
The code below finds the JAVA_COMMENT_OPEN_TAG
without any issues but has trouble finding the JAVA_COMMENT_CLOSE_TAG
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()); }
}