Reputation: 325
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.
Upvotes: 0
Views: 106
Reputation: 13334
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?
Upvotes: 3
Reputation: 16476
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());
Upvotes: 0
Reputation: 25623
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.
Upvotes: 1