Я хочу найти имя класса при чтении через .java-файл. Я не я возвращаюсь не матч прямо сейчас, используя это регулярное выражение:Regex: шаблон, чтобы найти Java-класс в .java-файле
\\s*[public][private]\\s*class\\s*(\\w*)\\s*\\{
Вот мой код до сих пор:
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class HW4Solution {
public static void main(String [] args){
//Prompt user for path to file.
File file = null;
Scanner pathScan = new Scanner(System.in);
while (file == null || !file.exists())
{
System.out.print("Enter valid file path: ");
file = new File(pathScan.next());
}
pathScan.close();
System.out.println("File: " + file.getPath() + " found.");
//Read file line by line into buffered reader
StringBuffer componentString = new StringBuffer(100);
String currentLine;
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(file.getPath()));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//TODO: Find class declarations
//TODO: Find superclasses
//TODO: Find instance variable declarations
//TODO: Find method signatures
//TODO: Find access modifier
//TODO: Find return type
//TODO: Find method name
//Creating patterns to look for!
//Class declarations
Pattern classDeclarationPattern = Pattern.compile("\\s*[public][private]\\s*class\\s*(\\w*)\\s*\\{");
try {
while((currentLine = bufferedReader.readLine()) != null){
Matcher classDeclarationMatcher = classDeclarationPattern.matcher(currentLine);
if(classDeclarationMatcher.group(1) != null){
componentString.append("Found class declaration: " + classDeclarationMatcher.group(3) + "\n");
/*if(classDeclarationMatcher.group(5) != null){
componentString.append("\tsuperclass: " + classDeclarationMatcher.group(5) + "\n");
}*/
System.out.println(classDeclarationMatcher.group());
}
}
}
catch (IOException e) {
e.printStackTrace();
}
finally{
try{
if (bufferedReader !=null) {
bufferedReader.close();
}
}
catch(IOException e){
e.printStackTrace();
}
}
System.out.println(componentString.toString());
}
}
В конце концов я хочу, чтобы иметь возможность определить, является ли объявление класса имеет суперкласса и Получите это тоже, но на данный момент у меня достаточно проблем (я не должен) получить название класса.
Вы никогда не называете 'find()' на совпадении. Это означает, что вы не ищете результатов. – jlordo
@iTech huh? '[class]' определенно не то, что он ищет –
@ kmaz13 вы понимаете, что это по существу эвристический метод и будет иметь ложные срабатывания (и, вероятно, ложные негативы)? –