简体   繁体   中英

Regular Expression For Detecting Recursive Java Functions

I am wondering what would be a regular expression that would detect any function declaration which has a body containing a call to itself in Java.

Example of a method that would match:

public int method()

{*n

method();

}*n

Thank you for any help.

Consider the following code samples:

public int method() {

System.out.prontln("method() started");
}

or

public int method() {

// this method() is just an example

}

Do you see now that you need a full-blown parser?

I don't see how this could be done reliably with a regular expression, since the arguments to any method call could be arbitrarily complex, and even include anyonymous classes containing similarly named methods.

So, the answer is "no"; at least not if you want it to be reliable.

This is a quick and dirty example. It would lead to many false positives and generally be slow. It doesn't take into account curly brackets and strings which could contain curlies. However, it works for your input. :-)

Matcher m = Pattern.compile("([\\w\\d_$]+\\s*\\([^)]*\\))[^{]*\\{.*\\1[^}]+}", Pattern.DOTALL |Pattern.MULTILINE).matcher(s1);

System.out.println(m.matches());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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