Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

Find method from .java file by java regex

I want to catch all methods from a .java file by regex. here is the code I have tried so far:

 public JavaMethodParser(String classContents) {
    Pattern classPattern = Pattern.compile("[a-zA-Z]*" + "\s*class\s+([_a-zA-Z]+)\s*\{(.*)}$", Pattern.DOTALL);

    // now match
    Matcher classMatcher = classPattern.matcher(classContents);
    //System.out.println("    "+classMatcher);
    if (classMatcher.find()) {
        String methodContents = classMatcher.group(2);
        // now parse the methods
        Pattern methodPattern = Pattern.compile("[a-zA-Z]*\s*[a-zA-Z]*\s+([_a-zA-Z]+)\s*?\(.*?\)\s*?\{");

        Matcher methodMatcher = methodPattern.matcher(methodContents);

        // creating method list and methodName list
        methodList = new ArrayList<>();
        methodNameList = new ArrayList<>();

        while (methodMatcher.find()) {
            String methodName = methodMatcher.group(1);
            String methodStart = methodMatcher.group();
            methodStartList.add(methodStart);
            methodNameList.add(methodName);
        }}`

`but the problem is if there is a file like:

public class Foo {
int q = 1;
Foo() {
    System.out.println("its foo class");
}
  void firstMethod(String s) {
    if (q == 1) {
        System.out.println("true");
    } else if (q > 1) {
        System.out.println("false");
    }
    else{
        System.out.println("nothing");
    }
}

if I want to catch foo() method it also catches if block and also if I want to catch void firstmethod() it also catches else if block and gives method name firstmethod and if. I want to catch only method name. I think in my regex there might occur other bugs if I test it in many different situations. Can anyone help me how can I solve those problem??any answer would be appreciated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...