1
我想在通過.java文件讀取時查找類的名稱。我就不會回來,現在比賽使用正則表達式:正則表達式:在.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 2013-02-14 22:38:18
@iTech吧? '[class]'絕對不是他正在尋找的 – 2013-02-14 22:38:56
@ kmaz13你意識到這實質上是一種啓發式方法,並且會有誤報(也可能是假陰性)? – 2013-02-14 22:40:11