gpt4 book ai didi

java - 仅用于开头 Java 文档注释的正则表达式

转载 作者:行者123 更新时间:2023-12-02 04:39:06 25 4
gpt4 key购买 nike

我正在尝试编写一个与 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()); }
}

最佳答案

您可以使用以下内容:

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

参见DEMO

关于java - 仅用于开头 Java 文档注释的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30403305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com