在Java實體類中批量刪除注釋可以使用正則表達式進行匹配替換操作。以下是一個示例代碼:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class RemoveComments {
public static void main(String[] args) {
String entityClass = "public class User {\n" +
" // This is a comment\n" +
" private String name;\n" +
"\n" +
" /*\n" +
" * This is a multi-line comment\n" +
" */\n" +
" private int age;\n" +
"\n" +
" // Another comment\n" +
" private String email;\n" +
"}";
String regex = "(\\/\\/.*$)|(\\/\\*.*?\\*\\/)";
Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.DOTALL);
Matcher matcher = pattern.matcher(entityClass);
String result = matcher.replaceAll("");
System.out.println(result);
}
}
上面的代碼會刪除Java實體類中的單行注釋(以//
開頭)和多行注釋(/*
和*/
之間的內容)。可以根據實際情況修改正則表達式來匹配其他類型的注釋。