简体   繁体   English

正则表达式:在.java文件中查找Java类的模式

[英]Regex: Pattern to find Java class in .java file

I want to find a class' name when reading through a .java file. 在阅读.java文件时,我想找到一个类的名称。 I'm returning no match right now using this regular expression: 我现在正在使用此正则表达式返回不匹配的内容:

\\s*[public][private]\\s*class\\s*(\\w*)\\s*\\{

Here is my code so far: 到目前为止,这是我的代码:

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());

    }
}

I eventually want to be able to determine if a class declaration has a superclass and get that too but for now I'm having enough trouble (which I shouldn't) getting the name of the class. 我最终希望能够确定类声明是否具有超类,并且也可以获取它,但是现在我遇到了很多麻烦(我不应该)来获取类的名称。

[public] is not matching what you think it should. [public]与您认为的不符。 It is a character class, which matches either of those characters in public . 它是一个字符类,与public中的任何一个字符匹配。 You should use pipe to match alternate words. 您应该使用pipe匹配替代词。

You can use following regex, extended to consider super classes or interface: - 您可以使用以下正则表达式进行扩展,以考虑super类或接口:-

Pattern.compile("\\s*(public|private)\\s+class\\s+(\\w+)\\s+((extends\\s+\\w+)|(implements\\s+\\w+( ,\\w+)*))?\\s*\\{");

Note that, you should use \\\\s+ with + quantifier when matching space between public|private and the class keyword. 请注意,在public|privateclass关键字之间匹配空格时,应使用\\\\s++量词。 Because you expect at least 1 space there. 因为您希望那里至少有1空间。 \\\\s* will match 0 space, which is not correct, since publicclass is not valid. \\\\s*将匹配0空间,这是不正确的,因为publicclass无效。

Apart from that, there can be some more options to consider here. 除此之外,这里还有更多选择可以考虑。 Like static inner classes , or generic classes , that will require minor modification in there, which you can do on your own. static inner classesgeneric classes ,在那里需要进行较小的修改,您可以自己进行修改。 I've just given a little insight on to how to approach. 我只是对如何处理提供了一些见解。


Also, one more important thing. 另外,还有一件重要的事情。 Before you can get the result from your group, you should call Matcher#find() method to do the actual matching. 在从组中获取结果之前,应调用Matcher#find()方法进行实际匹配。

RegExp for class declaration: 用于类声明的RegExp:

private String classRegExp = "(((|public|final|abstract|private|static|protected)(\\s+))?(class)(\\s+)(\\w+)(<.*>)?(\\s+extends\\s+\\w+)?(<.*>)?(\\s+implements\\s+)?(.*)?(<.*>)?(\\s*))\\{$";

for interface declaration: 用于接口声明:

private String interfaceRegExp = "(((|public|final|abstract|private|static|protected)(\\s+))?interface(\\s+)(\\w+)(<.*>)?(\\s+extends\\s+\\w+)?(<.*>)?(\\s+implements\\s+)?(.*)?(<.*>)?(\\s*))\\{$";

for enum declaration : 用于枚举声明:

private String enumRegExp = "((((public|final|private|static|protected)(\\s+))?enum(\\s+)(\\w+)?(\\s+implements\\s+\\w+)?(.*)?\\s*))\\{$";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM